在我的代码中有以下抽象超类
public abstract class AbstractClass<Type extends A> {...}
和一些儿童课程,例如
public class ChildClassA extends AbstractClass<GenericTypeA> {...}
public class ChildClassB extends AbstractClass<GenericTypeB> {...}
我正在寻找一种优雅的方式,如何以通用的方式在抽象类中使用子类的通用类型(GenericTypeA、GenericTypeB,...)。
为了解决这个问题,我目前定义了该方法
protected abstract Class<Type> getGenericTypeClass();
在我的抽象类中并实现了该方法
@Override
protected Class<GenericType> getGenericTypeClass() {
return GenericType.class;
}
在每个孩子的班级里。
是否可以在不实现此辅助方法的情况下获取抽象类中子类的泛型类型?
BR,
Markus
我认为这是可能的。我看到它与泛型一起用在 DAO 模式中。例如
考虑类:
public class A {}
public class B extends A {}
还有你的通用类:
import java.lang.reflect.ParameterizedType;
public abstract class Test<T extends A> {
private Class<T> theType;
public Test() {
theType = (Class<T>) (
(ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
// this method will always return the type that extends class "A"
public Class<T> getTheType() {
return theType;
}
public void printType() {
Class<T> clazz = getTheType();
System.out.println(clazz);
}
}
您可以有一个类 Test1,它用类 B 扩展了 Test(它扩展了 A)
public class Test1 extends Test<B> {
public static void main(String[] args) {
Test1 t = new Test1();
Class<B> clazz = t.getTheType();
System.out.println(clazz); // will print 'class B'
System.out.println(printType()); // will print 'class B'
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)