I’m not professional Java programmer, so this question could be simple, but I have searched the web for the answer but found nothing so far.
Lets say we have a generic class in Java:
public class C1 <T, U> {
public /*TYPE*/ f(T t, U u) {
return t.g(u)
}
The question is – how can I determine the type of the result of this generic example?
Is it somehow possible to write something like typeof(t.g(u))?
You cannot call
t.g(u)as is becauseTis an unbounded type. You need to put a compile-time bound on it so the compiler knows what methods are available. Otherwise you’ll only be able to callObjectmethods since the only thing the compiler can infer aboutTis that is extendsObject.For example, if you have an interface
G<U>with thegmethod you want to call:Then you would specify that
T extends G<U>, which lets you callg(). And now you know what the return type ofg()is: it’sR.If you want the result of
g()to be dependent on typesTandUthen you could do something like this: