【问题标题】:Determine Generic type with recursive call使用递归调用确定通用类型
【发布时间】:2017-01-17 11:19:30
【问题描述】:

我有一个有两个参数的方法:

public <P, T> T getT(P p, Class<T> returnType) {
    //This method converts p to an instance of the type T.
}

或多或少,代码遍历returnType的所有setter并调用p上的getter方法:

T t = new T();
t.setBla(p.getBla());

现在,在遍历 T 类的所有 setter 时,我遇到了一个 Collection。我想为集合中的每个项目递归地调用它自己的方法。 我的问题是,我无法指定返回类型,因为我无法确定收到的 Collection 的返回类型。像这样的东西(没有反射的伪代码):

for(Object o : list) {
    return getT(o, ???);
}

我尝试使用自定义注释来解决它,在该注释中我指定了该集合的 returnType,但我不能在我的注释中使用泛型:

public @interface ReturnType {
    public Class<?> value();
}

所以我在 getT() 中的论点不匹配。如何在不更改 getT() 方法 (getT(P p, Class t)) 的泛型类型的情况下解决此问题?

【问题讨论】:

    标签: java generics reflection


    【解决方案1】:

    如果您可以将泛型指定为另一个类的扩展,则可以改为这样编写:

    public <P, T> T getT(P p, Class<T extends SomeClass> returnType){
    //code
    }
    

    然后

    for(Object o : list) {
    return getT(o, SomeClass.class);
    }
    

    public @interface ReturnType { 
    public Class<SomeClass> value();
    } 
    

    【讨论】:

    • 感谢您的回答。我也意识到了这一点,但不幸的是我不能使用它。然而,我能够解决我的问题,但我还没有时间发布我的解决方案。最重要的是,在我发布我的解决方案之前,我想看看其他人的想法:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2023-04-03
    • 1970-01-01
    • 2011-08-26
    • 2019-06-27
    • 2019-03-08
    • 1970-01-01
    相关资源
    最近更新 更多