简体   繁体   中英

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:

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

Now, while looping over all setters of the T class, I come across a 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:

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

So my argument in my getT() doesn't match. How can I fix this without changing my generic type of the getT() method (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();
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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