Java中定义泛型<T>时,怎么获得泛型的类型

Python020

Java中定义泛型<T>时,怎么获得泛型的类型,第1张

T.getClass()或者T.class都是非法的,因为T是泛型变量。

由于一个类的类型是什么是在编译期处理的,故不能在运行时直接在Base里得到T的实际类型。

有一种变通的实现方式:

import java.lang.reflect.Array

import java.lang.reflect.ParameterizedType

import java.lang.reflect.Type

public class Generic extends Base<String>{

public static void main(String[] args) {

Generic c = new Generic()

System.out.println(c.array)

}

Object array

public Generic() {

array = Array.newInstance(getGenericType(0), 100)

}

}

class Base<T>{

public Class getGenericType(int index) {

Type genType = getClass().getGenericSuperclass()

if (!(genType instanceof ParameterizedType)) {

return Object.class

}

Type[] params = ((ParameterizedType) genType).getActualTypeArguments()

if (index >= params.length || index <0) {

throw new RuntimeException("Index outof bounds")

}

if (!(params[index] instanceof Class)) {

return Object.class

}

return (Class) params[index]

}

}

其中Base<T>是泛型类,在父类中声明getGenericType,子类继承具体的Base<String>,那么在子类中就可以通过getGenericType(0)获取到String的class.

获取java泛型中的对象类型,可以参考如下代码:

/**

* 通过反射取到 List<T> 中 T 的类型

* @param clazz

* @param field

* @return

*/

public static Class<? extends Object> getGenericType(Class<? extends Object> clazz, Field field){

Method getMethod = getGetMethodByField(clazz,field)

ParameterizedType pt= (ParameterizedType)getMethod.getGenericReturnType() 

        Class<? extends Object> type = (Class<?>)pt.getActualTypeArguments()[0]

        //System.out.println(type.getSimpleName())

        //System.out.println(type.getPackage())

        return type

}