在抽象超类中使用子类的泛型类型? [英] Using a generic type of a subclass within it's abstract superclass?
问题描述
在我的代码中,有以下抽象超类
Within my code a have the following abstract superclass
public abstract class AbstractClass<Type extends A> {...}
以及一些子类,例如
public class ChildClassA extends AbstractClass<GenericTypeA> {...}
public class ChildClassB extends AbstractClass<GenericTypeB> {...}
我正在寻找一种优雅的方式来使用通用类型
I'm searching for an elegant way how I can use the generic type of the child classes (GenericTypeA, GenericTypeB, ...) inside the abstract class in a generic way.
为了解决这个问题,我目前定义了方法
To solve this problem I currently defined the method
protected abstract Class<Type> getGenericTypeClass();
在我的抽象类中并实现了方法
in my abstract class and implemented the method
@Override
protected Class<GenericType> getGenericTypeClass() {
return GenericType.class;
}
每个孩子班级。
是否可以在不实现此辅助方法的情况下获得抽象类中子类的泛型?
Is it possible to get the generic type of the child classes in my abstract class without implementing this helper method?
BR,
马库斯
推荐答案
我认为这是可能的。我看到它与泛型一起在DAO模式中使用。例如
考虑类别:
I think its possible. I saw this was being used in the DAO patterns along with generics. e.g. Consider classes:
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类,该类通过类扩展了Test B(它扩展了A)
You can have a class Test1 that extends Test with class B (it extends 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'
}
}
这篇关于在抽象超类中使用子类的泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!