How to infer the specific return type of a method

2019-05-25 02:41发布

问题:

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?

回答1:

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.

ParameterizedType parameterizedType = (ParameterizedType) subClass.getGenericSuperclass();
09
  return (Class<?>) parameterizedType.getActualTypeArguments()[parameterIndex];

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.



回答2:

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