我正在使用 Spring 启动,我正在进行反射以提取包中以"存储库"结尾的类以及声明为MyGenericClass<T,R>
的所有字段。我的问题是我无法从myField
中提取ClassA
和ClassB
public class ContainerRepository{
private MyGenericClass<ClassA, ClassB> myField;}
我希望对以下对象运行相同的代码:
public class ProcessRepository{
private MyGenericClass<ClassC, ClassD> anotherField;}
并从anotherField
获得ClassC
和ClassD
简单的答案是,您无法在运行时使用反射推断泛型。但是,您可以轻松地将字段类型标记为实例变量(相当黑客,但不确定它是否有帮助(。
public class MyGenericClass<M, N> {
private M mType;
private N nType;
MyGenericClass (M m, N n){
this.mType = m;
this.nType = n;
}
public Class<?> getMType(){
return this.mType.getClass();
}
public Class<?> getNType(){
return this.nType.getClass();
}
}
参考资料:https://stackoverflow.com/a/26088911/2931410