4

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.

8
  • No. Otherwise you might close that topic as one with many questions. They provide separete subjects and expect different answers Commented May 26, 2014 at 8:35
  • 1
    I'm not sure I see the difference between the two questions. Commented May 26, 2014 at 8:50
  • I also don't get it to be honest Commented May 26, 2014 at 9:52
  • 1
    It is possible - you just need to grab a reference to the lambda before passing it into handle that way you can resolve the type argument for its class. Ex: TypeResolver.resolveRawArgument(Consumer.class, lambda.getClass());. See TypeTools for more usage info. Commented Dec 8, 2014 at 18:47
  • 1
    @ArtemBilan - Another option is to do the type resolution from inside your handle method: TypeResolver.resolveRawArgument(Consumer.class, consumer.getClass()); That should work. Commented Dec 8, 2014 at 19:19

1 Answer 1

5

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.

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

3 Comments

Good. I accepted the answer and go ahead with the solution
Yes it is possible to recreate the value of T since it's captured in the bytecode as part of the lambda's method invocation. See TypeTools for an example.
Agree with @Jonathan, you can get the types, they are erased through the usual methods of getting types, however that doesn't mean they are fully erased at runtime, they are still present and can be got through different means, e.g. docs.spring.io/spring-framework/docs/current/javadoc-api/org/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.