Java反射 - 在通用接口<t>中获取实际的T类型

时间:2018-01-23 18:55:51

标签: java generics reflection interface

如何在通用界面中获取实际的T类型?

鉴于以下课程:

class myClazz {
        private final IGenericInterface<?> genericInterface;

        myClazz(final IGenericInterface<otherClazz> genericInterface){
            this.genericInterface = genericInterface;
        }
}

如何使用反射从构造函数中获取otherClazz的简单名称?

我尝试了以下内容:

String otherClazzString = myClazz.class.getConstructors()[0].getParameterTypes()[0].toString(); // 

但我不知道接下来要做什么来获取通用接口中使用的实际类型的简单名称。

1 个答案:

答案 0 :(得分:1)

Close, but you need to use getGenericParameterTypes, as well as getDeclaredConstructors (since your constructor is not public):

Class<?> cls = (Class<?>) ((ParameterizedType) myClazz.class.getDeclaredConstructors()[0]
    .getGenericParameterTypes()[0]) // first constructor, first parameter
        .getActualTypeArguments()[0]; // first type argument

System.out.println(cls); // prints 'class otherClazz`

It should be noted that this code will only work if the type argument of the parameter is a concrete type, otherwise the cast to Class<?> will not work. For instance, in the case that the argument is a type variable, getActualTypeArguments()[0] will return an instance of TypeVariable instead of Class<...>.