(This is difficult to search because results are all about "method reference")
I want to get a Method
instance for a lambda expression for use with a legacy reflection-based API. The clousure should be included, so calling thatMethod.invoke(null, ...)
should have the same effect as calling the lambda.
I have looked at MethodHandles.Lookup, but it only seems to be relevant for the reverse transform. But I guess the bind
method may help to include the clousure?
Edit:
Say I have am lambda experssion:
Function<String, String> sayHello = name -> "Hello, " + name;
and I have a legacy framework (SpEL) that has an API like
registerFunction(String name, Method method)
which will call the given Method
with no this
argument (i.e. Method assumed to be static). So I'll need to get a special Method
instance that includes the lambda logic + the clousure data.
Well, lambda expressions are desugared into methods during compilation and as long as they don’t capture
this
(don’t access non-static
members), these methods will bestatic
. The tricky part is to get to these methods as there is no inspectable connection between the functional interface instance and its target method.To illustrate this, here the simplest case:
This works smoothly as there is only one lambda expression and hence, one candidate method. The name of that method is compiler specific and may contain some serial numbers or hash codes, etc.
On kludge is to make the lambda expression serializable and inspect its serialized form:
This works, however, serializable lambdas come at a high price.
The simplest solution would be to add an annotation to a parameter of the lambda expression to be found when iterating over the methods, however, currently,
javac
doesn’t store the annotation properly, see also this question about this topic.But you may also consider just creating ordinary
static
methods holding the code instead of a lambda expression. Getting aMethod
object for a method is straight-forward and you still can create a functional interface instance out of them using method references…In case you don't find an elegant way, here is the ugly way (Ideone). Usual warning when reflection is involved: may break in future releases etc.