How to extract a Generic type from arg
I have a method signature that looks like
public void (Foo<T> foo)
In this method I need to call a method that takes
Class<T> clazz
as an argument.开发者_JAVA技巧 How can I get a reference of type Class<T>
from foo? Thanks
Due to type erasure, you cannot get directly at type parameters. The information is simply not present at runtime. API that needs reference to type parameter's class needs to take class object instance...
public void abc(Foo<T> foo, Class<T> clazz)
Are you sure that your method signature is correct?
I think that without class T you cannot make argument looks like
public void method(Class<T> obj){
}
The type of argument must be present, so you already know the type of incoming.
When you change it into this:
public <T> void method(T u){
System.out.println("U: " + u.getClass().getName());
}
You should be able to get class name or just class reference, not?
Docs:
http://download.oracle.com/javase/tutorial/java/generics/genmethods.html
精彩评论