我必须编写一个实用程序方法,该方法可以从对象中获取特定的变量值, 在评估一些条件上。
以下是要求。
当前解决方案:
public Object getFieldValue(String type, IDTO dto){
Method method = dto.getClass().getMethod("get"+createMethodName(type));
Object returnedObject = method.invoke(dto, null);
return returnedObject;
}
但是,操作非常繁重,并且会带来性能问题。有没有其他选择可以选择,或者有更好的方法可以做到这一点。
其他要点:
答案 0 :(得分:1)
如果需要性能,我建议对实用程序方法使用代码生成,以对IDTO对象进行所需的访问。通常这将被集成到构建中。您生成的方法可以对每个“类型”使用性能良好的switch语句,例如:
/**
* Utility for generic access to IDTO object properties.
* GENERATED code, do not change! See template ....
*/
public Object getFieldValue(String type, IDTO dto){
switch (type) {
case "name" : return dto.getName();
case "subtype" : return dto.getSubtype();
...
}
// ERROR handling
throw new RuntimeException("unknown property");
}
要实现生成器代码,可以使用与上面代码相同的方式来使用反射。 对于该方法的更广泛使用,我建议引入一个简单的模板引擎,例如,参见https://freemarker.apache.org