如何将参数化类型类参数转换为其子类形式? 我读过很多关于提取类型参数的值的示例和问题,您应该有一个接口(interface)或抽象类,您应该从中扩展。
考虑下面的代码
type = (Class<T>) ((ParameterizedType)(getClass().getGenericSuperclass())).getActualTypeArguments()[0];
使用上面的代码,您可以将“type”变量转换为 (Class
下面是完整的实现,其中 Person 类是传递到通用父类(super class)类型参数参数的值。当我创建通用子类的实例并我传递 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>();
}
}
通用 super 抽象类
public abstract class GenericAbstractSuper<T> {
}
拜托,我真的需要一些帮助。我找不到类似的问题。
最佳答案
您需要创建 GenericSubClass
的子类、匿名或其他方式。
GenericSubClass<Student> genStud = new GenericSubClass<Student>(){};
现在
getClass().getGenericSuperclass()
将返回 Type
对于 GenericSubClass<Student>
你可以提取Student
.
以前,
getClass().getGenericSuperclass()
正在返回GenericAbstractSuper<Person>
所以你正在提取 Person
.
此技巧用于类型标记。
关于java - 提取参数化类型的值时,将参数化类型类参数转换为子类形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570889/