1

我正在使用 Spring boot,并且正在进行反射以提取以“Repository”结尾的包中的类,并且所有字段都声明为MyGenericClass<T,R>. ClassA我的问题是我无法ClassBmyField

public class ContainerRepository{
private MyGenericClass<ClassA, ClassB> myField;}

我希望针对以下内容运行相同的代码:

public class ProcessRepository{
private MyGenericClass<ClassC, ClassD> anotherField;}

并从ClassC_ClassDanotherField

4

1 回答 1

2

简单的答案,您不能在运行时使用反射推断泛型。但是,您可以轻松地将您的字段类型标记为实例变量(相当 hack,但不确定它是否有帮助)。

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

于 2018-05-02T08:30:14.847 回答