我一直在使用动态LINQ,我想知道在Java中是否有可能做类似的事情。例如,如果我使用以下工作代码:
Stream<PoliceShooting> averageAge = peopleShot.stream().filter(t->t.getAge() != null);
有没有办法像使用动态LINQ一样使它动态化
String dynamicGetter = "t.getAge() != null"
Stream<PoliceShooting> averageAge = peopleShot.stream().filter(t->dynamicGetter);
答案 0 :(得分:0)
根据How to convert a string to a lambda expression?中的建议,依靠Nashorn,您可以定义一种方法来根据JavaScript代码构建// save data as text file to Alluxio
> rdd.saveAsTextFile("alluxio://localhost:19998/rdd1")
// read data as text file from Alluxio
> rdd = sc.textFile("alluxio://localhost:19998/rdd1")
// save data as object file to Alluxio
> rdd.saveAsObjectFile("alluxio://localhost:19998/rdd2")
// read data as object file from Alluxio
> rdd = sc.objectFile("alluxio://localhost:19998/rdd2")
:
Predicate
,然后将其用作:
public Predicate<Object> convertJSToPredicate(String js) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
return (Predicate<Object>) engine.eval("new java.util.function.Predicate(function(t) " + js + ")");
}
当然String dynamicGetter = "t.getAge() != null";
Stream<PoliceShooting> averageAge = peopleShot.stream()
.filter(convertJSToPredicate(dynamicGetter));
必须是JavaScript而不是Java代码,并且可以通过变量dynamicGetter
访问传入的对象。
请注意,Nashorn was deprecated in Java 11。我以为会有其他的实现方式。