java中如何得到泛型参数的class?

Python019

java中如何得到泛型参数的class?,第1张

泛型的类型是无法在运行时通过反射取得的,泛型类型在编译成字节码的时候已经被虚拟机给去掉了,只是起到提示编译器进行类型检查的作用

用这种方法你试一试:父类:import java.lang.reflect.ParameterizedType

public class Parent<T {

public Parent() {

ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass()

System.out.println("type==" + type)

System.out.println("entityClass==" + type.getActualTypeArguments()[0])

System.out.println("getOwnerType==" + type.getOwnerType())

System.out.println("getRawType==" + type.getRawType())}}子类:public class Child<T extends Parent<String {

package com.leo.common

public class Genericity<T>{

public static void main(String[] args) {

Genericity<String>test = new Genericity<>("test1")

System.out.println(test.getGenericityName())

Genericity<Double>test1 = new Genericity<>(new Double(123))

System.out.println(test1.getGenericityName())

}

private T data

public Genericity(T data) {

this.data = data

}

public T getData() {

return this.data

}

public String getGenericityName() {

return data.getClass().getName()

}

}

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.