0

如何将参数化类型类参数转换为其子类形式?我已经阅读了很多关于提取类型参数值的示例和问题,你应该有一个接口或抽象类,你应该从中扩展

考虑下面的代码

type = (Class<T>) ((ParameterizedType)(getClass().getGenericSuperclass())).getActualTypeArguments()[0];

使用上面的代码,您可以将“类型”变量转换为 (Class<T>) 表示的内容。假设 <T> 是Person.class

下面是完整的实现,其中 Person 类是传递给通用超类类型参数参数的值。当我创建泛型子类的实例并传递 Person 类型参数参数的子类时,它总是被强制转换为 Person。type == Student.class打印false或者即使我打印类型,它总是打印Person不是Student。我怎样才能做到这一点?我想要的东西是可能的吗?

通用子类

public class GenericSubClass<T extends Person> extends GenericAbstractSuper<Person> {

public Class<T> type;

@SuppressWarnings("unchecked")
public GenericSubClass() {

    type = (Class<T>) ((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[0];

    System.out.println(type.getSimpleName());
    System.out.println(type == Student.class);
} 

public static void main(String[] args) {

    GenericSubClass<Student> genStud = new GenericSubClass<Student>();
 // GenericSubClass<Employee> genEmp = new GenericSubClass<Employee>();
 // GenericSubClass<Person> genPer = new GenericSubClass<Person>();
  }
}

通用超抽象类

public abstract class GenericAbstractSuper<T> {
}

请我真的需要一些帮助。我找不到类似的问题。

4

1 回答 1

3

你会想要创建一个你的GenericSubClass、匿名的或其他的子类。

GenericSubClass<Student> genStud = new GenericSubClass<Student>(){};

现在

getClass().getGenericSuperclass()

将返回一个TypeforGenericSubClass<Student>并且您可以提取Student.

之前,

getClass().getGenericSuperclass()

正在返回GenericAbstractSuper<Person>,所以您正在提取Person.

这个技巧用于类型标记

于 2014-08-29T15:19:24.893 回答