Christian Schlichtherle
Christian Schlichtherle

Reputation: 3155

How to infer the specific return type of a method with a generic return type?

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?

Upvotes: 2

Views: 451

Answers (2)

Christian Schlichtherle
Christian Schlichtherle

Reputation: 3155

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

Upvotes: 0

A_C
A_C

Reputation: 925

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.

Upvotes: 2

Related Questions