Java:使用lambda参数获取实际类型的泛型方法 [英] Java: get actual type of generic method with lambda parameter
问题描述
我问了一些关于 lambdas
的问题,这里 Java:如何解析泛型类型的lambda参数?,但这个有点不同。
我有方法签名:
public< P>无效句柄(消费者< P>消费者){
...
}
我可以用 lambda
:
。< Integer>句柄(p - > System.out.println(p * 2));
我可以以某种方式解决实际的泛型类型吗?
我的意思是我想在 handle
方法中获得 Integer.class
。
顺便说一句,我可以像这样解决问题:
public< P> void handle(Class< P> pClass,Consumer< P> consumer){...}
.handle(Integer.class,p - > System.out.println(p * 2)) ;
但是,如果我们将lambda更改为内联实现,它看起来并不看好。
不,这是不可能的。你不能得到像 T.class
,因为泛型在运行时被擦除。你真的需要传入 Class< T>
才能够获得这个类。
一个XY问题。也许你真的需要类的类型,但没有进一步的信息,这有点味道。
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.
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.
这篇关于Java:使用lambda参数获取实际类型的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!