假设我有以下课程:
class Person {
int age;
String city;
Collection<Person> friends;
Person spouse;
}
我需要一个库,它允许我评估给定Person对象上的逻辑表达式是否为真。表达式看起来像这样:
((age>25 OR spouse.age>27) AND city=="New-York" AND size(friends)>100)
所以,要求是:
建议?
答案 0 :(得分:4)
您可以使用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;
}
}
答案 1 :(得分:3)
好吧,想想我找到了我想要的东西,这是对assylias答案的一个变化,但我更喜欢它,因为它更标准化(不想特别依赖于Javascript表达式,或根本就运行Javascript)。
显然有一个Unified Expression Language用于评估表达式,它最初是为JSP设计的,但也可以用于其他东西。有几个解析器实现,我可能会使用Spring EL或JUEL