您可以使用ScriptEngine + 反射:
- 访问对象中的所有字段并创建具有这些值的变量
- 评估表达式
这是一个人为的例子,它输出:
age = 35
city = "London"
age > 32 && city == "London" => true
age > 32 && city == "Paris" => false
age < 32 && city == "London" => false
如果您想处理非原始类型(例如集合),它可能会变得非常混乱。
public class Test1 {
public static void main(String[] args) throws Exception{
Person p = new Person();
p.age = 35;
p.city = "London";
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Class<Person> c = Person.class;
for (Field f : c.getDeclaredFields()) {
Object o = f.get(p);
String assignement = null;
if (o instanceof String) {
assignement = f.getName() + " = \"" + String.valueOf(o) + "\"";
} else {
assignement = f.getName() + " = " + String.valueOf(o);
}
engine.eval(assignement);
System.out.println(assignement);
}
String condition = "age > 32 && city == \"London\"";
System.out.println(condition + " => " + engine.eval(condition));
condition = "age > 32 && city == \"Paris\"";
System.out.println(condition + " => " + engine.eval(condition));
condition = "age < 32 && city == \"London\"";
System.out.println(condition + " => " + engine.eval(condition));
}
public static class Person {
int age;
String city;
}
}