4

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

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.