Java: get actual type of generic method with lambda parameter

generics, java, lambda

Solution

No, this is not possible.

You cannot get something like `T.class`, because generics are erased at runtime. You really need to pass in `Class<T>` to be able to get the class itself.

I also smell an XY-problem. Perhaps you really need the class type, but without further information, this smells a little bit.

Problem

I asked some question about `lambdas` here Java: how to resolve generic type of lambda parameter?, but this one is a bit different. I have the method signature: ``` public <P> void handle(Consumer<P> consumer) { ... } ``` I can use it with `lambda`: ``` .<Integer>handle(p -> System.out.println(p * 2)); ``` Can I somehow resolve that actual generic type? I mean I want to get `Integer.class` within that `handle` method. BTW I can resolve the issue like this: ``` public <P> void handle(Class<P> pClass, Consumer<P> consumer) {...} .handle(Integer.class, p -> System.out.println(p * 2)); ``` But it doesn't look kosher, if we change the lambda to inline implementation.

Original source

Related problems