我正在尝试注入现有代码并执行一串附加的java代码,这些代码使用我的项目中定义的类并操作我的“编译”代码中提供的数据。 我尝试过使用 beanshell,但在使用现有类时遇到了一些问题(除了使用 lambda 函数、钻石运算符等问题)。 我知道这根本不安全,但我将其用于测试目的。 这就是我的代码现在的样子:
DiscoverViewModel viewModel = new ViewModelProvider(viewModelStoreOwner).get(DiscoverViewModel.class);
try {
ArrayList<EntityConsumedThings> things = new ArrayList<>();
viewModel.getAllThingsLiveData().observe((LifecycleOwner) context,
things::addAll);
Map<String, ConsumedThing> consumedThingMap = new HashMap<>();
for (EntityConsumedThings t : things) {
ConsumedThing consumedThing = WotInteraction.getInstance(context).getWot().consume(Thing.fromJson(t.thingJSON));
consumedThingMap.put(consumedThing.getId(), consumedThing);
}
} catch (WotException | JSONException ex){
ex.printStackTrace();
}
// EXAMPLE CODE - IT WILL BE AUTOGENERATED AND RETRIEVED FROM A SERVER
String code = "ConsumedThing consumedThing = consumedThingsMap.get(\"urn:uuid:92e5b68f-322a-433a-8cff-f50f6ca1b519\");" +
"if(consumedThing!=null){" +
"ConsumedThingProperty property = consumedThing.getProperty(\"resources\");" +
"property.read();\n" +
"} else {\n" +
" System.out.println(\"RUNTIME ERROR: Thing not found.\");\n" +
" }\n;";
// EXECUTE THE CODE HERE
ConsumedThing、ConsumedThingProperty 类在我的项目中定义。 有没有办法做我想做的事情或者这是不可能的? 预先感谢任何人都会回答我。
我只需在 beanshell 脚本中导入我需要的类,并将代码中实例化的变量传递到 beanshell 上下文。
DiscoverViewModel viewModel = new ViewModelProvider(viewModelStoreOwner).get(DiscoverViewModel.class);
// EXAMPLE CODE - IT WILL BE AUTOGENERATED AND RETRIEVED FROM A SERVER
String code = "import com.example.wot_servient.wot.thing.ConsumedThing;\n"+
"import com.example.wot_servient.wot.thing.action.ConsumedThingAction;\n" +
"import com.example.wot_servient.wot.thing.property.ConsumedThingProperty;\n" +
"ConsumedThing consumedThing = consumedThingsMap.get(\"urn:uuid:92e5b68f-322a-433a-8cff-f50f6ca1b519\");" +
"if(consumedThing!=null){" +
"ConsumedThingProperty property = consumedThing.getProperty(\"resources\");" +
"property.read();\n" +
"} else {\n" +
" System.out.println(\"RUNTIME ERROR: Thing not found.\");\n" +
" }\n;";
// EXECUTE THE CODE HERE
Executors.newSingleThreadExecutor().execute(() -> {
try {
List<EntityConsumedThings> things = viewModel.getAllThingsList();
Map<String, ConsumedThing> consumedThingsMap = new HashMap<>();
for (EntityConsumedThings t : things) {
ConsumedThing consumedThing = WotInteraction.getInstance(context).getWot().consume(Thing.fromJson(t.thingJSON));
consumedThingsMap.put(consumedThing.getId(), consumedThing);
}
Interpreter interpreter = new Interpreter();
interpreter.set("consumedThingsMap", consumedThingsMap);
interpreter.eval(code);
} catch (WotException | JSONException | EvalError ex){
ex.printStackTrace();
}
});