Artem Bilan Artem Bilan - 1 year ago 96
Java Question

Java: how to resolve generic type of lambda parameter?

Well, we have


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
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
(in the mentioned
), 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

The method
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download