vendredi 15 mai 2020

Resolve generic return type of method at runtim

In a situation where the generic return type of a method only depends on the types of the input parameters (not on the class type parameters), how can I resolve the generic type to the actual type given a concrete list of parameters?

Let's say I have a method like this

public <T,S extends T> T doSomething(T input, S derivedInput)

and at Runtime I have a Method object representing this method as well as some parameter objects so that I can invoke the method with reflection

Object returnval = m.invoke(instance,Object[]{x,y});

Because the return type is determined by the types of the inputs and given that I know the actual types of x and y at runtime, I should be able to figure out at runtime what the type of returnval actually is, or at least a more specific superclass of the actual type than Object. In the example, I would expect there to be a way to automatically infer the class x.Class() from m, x and y, assuming of course that x and y really satisfy the type constraint in the method definition, but ideally I would also be able to tell at runtime if they violate it.

Now I know that there is Method#getGenericReturnType and Method#getGenericParameterTypes, but I could not figure out how to use those to make the inference I want. I also know that this won't work if there is a type parameter of the class involved since those get erased. So I won't be able to resolve the T in T List<T>.get(int) given only a list and an integer. But if the return type is only dependent on the parameter types, I think it should be possible.





Aucun commentaire:

Enregistrer un commentaire