Artem Bilan Artem Bilan - 3 months ago 10
Java Question

Java: how to resolve generic type of lambda parameter?

Well, we have

FunctionalInterface
:

public interface Consumer<T> {

void accept(T t);

}


And I can use it like:

.handle(Integer p -> System.out.println(p * 2));


How can we resolve the actual
generic type
of that lambda parameter in our code?

When we use it as an inline implementation it isn't so difficult to extract the
Integer
from the method of that class.

Do I miss anything? Or just java doesn't support it for lambda classes ?

To be more cleaner:

That lambda is wrapped with
MethodInvoker
(in the mentioned
handle
), which in its
execute(Message<?> message)
extracts actual parameters for further reflection method invocation. Before that it converts provided arguments to target params using Spring's
ConversionService
.

The method
handle
in this case is some configurer before the real application work.

The different question, but with expectation for the solution for the same issue: Java: get actual type of generic method with lambda parameter

Answer

I recently added support for resolving lambda type arguments to TypeTools. Ex:

MapFunction<String, Integer> fn = str -> Integer.valueOf(str);
Class<?>[] typeArgs = TypeResolver.resolveRawArguments(MapFunction.class, fn.getClass());

The resolved type args are as expected:

assert typeArgs[0] == String.class;
assert typeArgs[1] == Integer.class;

Note: The underlying implementation uses the ConstantPool approach outlined by @danielbodart which is known to work on Oracle JDK and OpenJDK.

Comments