0

I am trying to develop an http-library, mainly for getting a clue about how they work.

I am currently trying to automatically implement interfaces in which the methods look like this:

public Response<ExampleObject> getInformationAsExampleObject();

The interface is implemented and an InvocationHandler is created for each method.

Here is the problem: I haven't found a straightforward way to get the Class<?> for the T of the generic. In the example above it would be ExampleObject.class

It would be pretty simple if I was given an initialized object, but instead I am dealing with an unimplemented interface.

I have resorted to this:

Class.forName(Arrays.stream(((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()).toList().get(0).getTypeName());

and it feels like there has to be a more straightforward way to achieve the same result. The question is how.

GeoMldr
  • 50
  • 6
  • You may want to read about [type erasure](https://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens) – Matteo NNZ Mar 17 '23 at 14:29
  • See the duplicate. To summarise, you don't need `Class.forName` or the stream. Just access the array returned by `getActualTypeArgument` directly with `[0]`, and cast that to `Class>`. – Sweeper Mar 17 '23 at 14:37

0 Answers0