使用反射获取泛型类

时间:2014-06-16 15:54:12

标签: java generics reflection deserialization

在这种情况下,如何使用反射获取通用类型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

0 个答案:

没有答案