I would like to get instance of functional interface, e.g. Predicate from String. For example user types lambda expression in text field of UI for filtering some list of numbers list.stream().filter("lambda here")
1 Answer
There isn't a straight forward way to do this. Java hasn't turned in to some dynamic language I'm afraid.
You could use the Java Compiler API present since JDK6, to compile a the snippet of code into a class that implements Predicate and load it on the fly, but it won't be pretty.
1 Comment
Stuart Marks
Right. One of the ways it "won't be pretty" is that a lambda expression really cannot be compiled in isolation; it has to have a target type from which the compiler can do type inference. For example, asking the compiler to compile the lambda expression
x -> false won't work, because there's no way for the compiler to determine the type of x. It might work to have the UI implicitly add a cast to a functional interface that specifies type arguments, e.g. (Predicate<String>)(x -> false).