简体   繁体   English

使用递归调用确定泛型类型

[英]Determine Generic type with recursive call

I have a method that has two arguments:我有一个有两个参数的方法:

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

More or less, the code goes over all setters of the returnType and calls the getter method on the p:或多或少,代码遍历 returnType 的所有 setter 并调用 p 上的 getter 方法:

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

Now, while looping over all setters of the T class, I come across a Collection.现在,在遍历 T 类的所有 setter 时,我遇到了一个 Collection。 I want to recursively recall its own method for each item in the Collection.我想为集合中的每个项目递归地调用它自己的方法。 My problem is, that I can't specify the return type since I can't figure out the return type of the Collection I receive.我的问题是,我无法指定返回类型,因为我无法弄清楚我收到的集合的返回类型。 Something like this (pseudocode without reflection):像这样(没有反射的伪代码):

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

I tried solving it with a custom annotation where I specifiy the returnType of that collection, but I can't use generics in my Annotation:我尝试使用自定义注释来解决它,我在其中指定了该集合的 returnType,但我不能在我的注释中使用泛型:

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

So my argument in my getT() doesn't match.所以我在 getT() 中的论点不匹配。 How can I fix this without changing my generic type of the getT() method (getT(P p, Class t))?如何在不更改 getT() 方法(getT(P p, Class t))的通用类型的情况下解决此问题?

If you can specify your generic as an extention of another class, you can instead write something like this:如果您可以将泛型指定为另一个类的扩展,则可以改为编写如下内容:

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

then然后

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

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM