Given the following interface:
interface Random extends java.util.function.Supplier<Integer> { }
with java.util.function.Supplier
looking like this (abbreviated):
public interface Supplier<T> { T get(); }
Now consider the following:
java.lang.reflect.Method get = Random.class.getMethod("get");
System.out.println(get.getReturnType()); // prints `class java.lang.Object`
System.out.println(get.getGenericReturnType()); // prints `T`
How can I infer that the return type should actually be java.lang.Integer
?
You can probably do this with something like below code. The idea here is that the generic type information is potentially available in the byte code and can be accessed at runtime. Refer the link below for more details.
https://www.javacodegeeks.com/2013/12/advanced-java-generics-retreiving-generic-type-arguments.html
There are some other useful articles online which describe this too.
Ankur's response is correct in that it provides a hint to the technology to use. However, a generic solution which covers all the edge cases is pretty complex, which justifies the need for a small library.
After researching the subject more, I have found this excellent solution: https://github.com/leangen/geantyref#getting-the-exact-return-type-of-a-method