我正在尝试在mvel脚本中创建一个新对象。我有一个名为 Entity 的类,该类对类型为 StatusReasonParameters 的变量的引用。我想填充要传递给MVEL表达式的整个Entity类对象。 如果我在表达式中执行 new StatusReasonParameters(),则会出现以下错误 错误:未知类或非法声明:org.mvel2.ParserContext sts = new StatusReasonParameters()。 我还尝试过通过 ParserContext 导入类,也尝试过使用StatusReasonParameters.class.newInstance(),但无济于事。如果无法添加新实例,那么新的HashMap()会如何工作?
public class Entity {
private String id;
private EntityStatus status;
private StatusReasonParameters statusReasonParameters;
}
public class StatusReasonParameters {
private String reason;
private String explanation;
}
MVEL expression
if(null != name) {
entity.name = name;
}
if(null != status) {
entity.status = status;
entity.status(EntityStatus.valueOf(status));
}
if(null != statusReason) {
sts = new StatusReasonParameters();
sts.reason = statusReason;
entity.statusReasonParameters = sts;
}
fieldsData = new HashMap();
if(null != outletName) {
outlets = [];
outletData1 = [];
outletData1.name = outletName;
if(null != outletRegion) {
outletData1.outletRegion = outletRegion;
}
outlets[0] = outletData1;
}
bs = new BasicDBObject(fieldsData);
entity.fields = bs;
Here is the main method
Map<String,Object> map = new HashMap<>();
map.put("name", "nitin");
map.put("status", "DRAFT");
map.put("statusReason", "BHOT BADIYA");
map.put("statusExplanation", "explanation is this");
map.put("outletName", "outlet1");
map.put("outletRegion", "lucknow");
map.put("entity", entity);
ParserContext parseContext = new ParserContext();
parseContext.addImport(StatusReasonParameters.class);
parseContext.addImport(BasicDBObject.class);
parseContext.addImport(EntityStatus.class);
String expression = "new HashMap();if(null != name) {\\r\\n entity.name = name;\\r\\n}\\r\\nif(null != status) {\\r\\n entity.status = status;\\r\\n entity.status(EntityStatus.valueOf(status));\\r\\n}\\r\\n\\r\\nif(null != statusReason) {\\r\\n sts = StatusReasonParameters.class.newInstance();\\r\\n sts.reason = statusReason;\\r\\nentity.statusReasonParameters = sts;\\r\\n}\\r\\nfieldsData = new HashMap(); \\r\\nif(null != outletName) {\\r\\n outlets = [];\\r\\n outletData1 = [];\\r\\n outletData1.name = outletName;\\r\\nif(null != outletRegion) {\\r\\noutletData1.outletRegion = outletRegion; \\r\\n}\\r\\n outlets[0] = outletData1;\\r\\n}\\r\\nbs = new BasicDBObject(fieldsData);\\r\\nentity.fields = bs;";
Serializable com = MVEL.compileExpression(expression,parseContext);
MVEL.executeExpression(com, map);
System.out.print(entity);