How to infer the specific return type of a method

2019-05-25 02:12发布

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?

2条回答
Explosion°爆炸
2楼-- · 2019-05-25 03:03

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.

查看更多
混吃等死
3楼-- · 2019-05-25 03:05

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

查看更多
登录 后发表回答