在这种情况下,如何使用反射获取通用类型Collection
的类名?
public class MyClass<T> implements TheirClass<Collection<T>> {
...
public Class<?> getCollectionType() {
//Need to use reflection on `this` in order to return the proper class
//of the type of Collection
}
}
当我们将MyClass指定为Collection类型时,在下面:
MyClass<Collection<AnotherClass>> me = new MyClass<>();
结果如下所示:
MyClass<Collection<AnotherClass>> meAnotherClass = new MyClass<>();
MyClass<Collection<String>> meString = new MyClass<>();
System.out.println(""+meString.getCollectionType().getClass() == String.class); //true
System.out.println(""+meAnotherClass.getCollectionType().getClass() == AnotherClass.class); //true