【问题标题】:Extract Multiple Generic Types from a Field in Java从Java中的字段中提取多个泛型类型
【发布时间】:2018-05-02 08:14:34
【问题描述】:

我正在使用 Spring Boot,并且我正在做反射以提取我的包中以“Repository”结尾的类以及声明为 MyGenericClass<T,R> 的所有字段。我的问题是我无法从myField 中提取ClassAClassB

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

我希望运行相同的代码:

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

并从anotherField 获取ClassCClassD

【问题讨论】:

标签: java spring spring-boot generics


【解决方案1】:

简单的答案,您不能在运行时使用反射推断泛型。但是,您可以轻松地将您的字段类型标记为实例变量(相当 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

【讨论】:

  • 你也可以在获取方法中返回Class&lt;?&gt;
猜你喜欢
  • 2021-07-17
  • 2022-07-04
  • 1970-01-01
  • 2022-06-15
  • 2011-01-24
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
  • 2013-04-17
相关资源
最近更新 更多