在java中,使用泛型,比如说T,但是T.class就要报错。我想获取T的class对象怎样获取啊。
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 BaseString {
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 BaseT {
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];
}
}
其中BaseT是泛型类,在父类中声明getGenericType,子类继承具体的BaseString,那么在子类中就可以通过getGenericType(0)获取到String的class.
java 如何获取 泛型的 class
package com.leo.common;
public class GenericityT {
public static void main(String[] args) {
GenericityString test = new Genericity(“test1”);
System.out.println(test.getGenericityName());
GenericityDouble 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();
}
}
java 怎么获取t的class
1. public Type getGenericSuperclass()
用来返回表示当前Class 所表示的实体(类、接口、基本类型或 void)的直接超类的Type。如果这个直接超类是参数化类型的,则返回的Type对象必须明确反映在源代码中声明时使用的类型。比如:
import java.lang.reflect.ParameterizedType;
public class GT1 extends GT2Integer{
public static void main(String[] args) {
System.out.println(((ParameterizedType)new GT1().getClass().getGenericSuperclass()));
}
}
则输出结果即为:
GT2java.lang.Integer
如果此Class代表的是Object 类、接口、基本类型或 void,则返回 null。。如果此对象表示一个数组类,则返回表示 Object 类的 Class 对象。
2. public Type[] getGenericInterfaces()
与上面那个方法类似,只不过Java的类可以实现多个接口,所以返回的Type必须用数组来存储。
以上两个方法返回的都是Type对象或数组,在我们的这个话题中,Class都是代表的参数化类型,因此可以将Type对象Cast成ParameterizedType对象。而 ParameterizedType对象有一个方法, getActualTypeArguments()。
public Type[] getActualTypeArguments()
用来返回一个Type对象数组,这个数组代表着这个Type声明中实际使用的类型。接着使用上面的例子:
import java.lang.reflect.ParameterizedType;
public class GT1 extends GT2Integer{
public static void main(String[] args) {
System.out.println(((ParameterizedType)new GT1().getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
}
}