Search code examples
java-8predicatenashornjavascript-engine

How to create and return Predicate<T> from withing Nashorn engine java 8


How to create a Predicate from ScriptEngine in java 8 and return it to java program?

Predicate conditions are operators and their comparing values and are good in number. So I wanted to get the predicate from javaScript Engine something like below:

public Predicate<Object> getPredicate(String operator, String value) {
return Predicate<Object> engine.eval("(i)-> i" + operator + value);
}

here operator can be >=, <=,>,< etc. this is just a simpler version of the actual problem. How can i create predicates from nashorn, i'll be able drive after this.


Solution

  • This should work:

    engine.eval("new java.util.function.Predicate(function(i) { return i" + operator + value + ";})");
    

    Also, I think in your original post you didn't want to quote "value".