I have the following:
public class Foo<T extends Grok> extends ArrayList<T> {
}
How can I find the class name represented by T at runtime? For instance, let's say I allocate like this:
Foo<Apple> foo = new Foo<Apple>();
Is there a way I can get Apple as the class name used 开发者_如何学编程in the constructor of Foo?:
public Foo() {
super();
String classname = this.getTypeClassName(); // "com.me.Apple"
}
I could just add a method to set the classname, but would prefer to fetch it internally so the user doesn't have to do it,
Thank you
Due to type erasure (one of the gaps in Java's generics model), this is impossible in the general case. If foo
is passed an instance of T, it can inspect that instance's type, but there is no guarantee that it will be exactly T and not a derived type. Since you are trying to access the type in the constructor at which point it can't possibly be holding such an instance, so you would have to pass an apple in through the constructor.
Marcelo's answer explains that you can't do this like you want, due to type erasure. However, there are other options for doing what you want, like this:
public class Foo<T extends Grok> extends ArrayList<T> {
private Foo(Class<T> type) {
String classname = type.getName();
...
}
public static <T extends Grok> Foo<T> create(Class<T> type) {
return new Foo<T>(type);
}
...
}
This enables clients of the class to just write the following, which is approximately the same effort as the normal constructor but gives you your type name too.
Foo<Apple> foo = Foo.create(Apple.class);
精彩评论