假设我有以下类(class):
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)
所以,要求是:
- 能够使用基本的逻辑运算符
- 访问给定对象的属性
- 访问内部对象的属性
- 使用简单的数学\类似 sql 的函数,例如 size、max、sum
建议?
最佳答案
你可以使用 ScriptEngine + 反射(reflection):
- 访问所有fields在您的对象中创建具有这些值的变量
- 评估表达式
这是一个输出的人为例子:
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;
}
}
关于java - 用于评估 Java 对象上的逻辑表达式的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12691398/