0

I know that for get a class name from a java Class I can do MyClass.class, but I cannot do this on parametrized class. For example I want to do ParametrizedClass<MyClass>.class.

Anyone knows if this is possible?

I want to get class from parametrized class for generating Swagger documentation.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 3
    No, it is not, and is not necessary. The generic parameter does not influence the `.class` object. Generics in Java are different from, e.g., template parameters in C++ where each parameterized instance generates a separate "class". – Turing85 Jun 06 '23 at 20:28
  • [`ideone.com` demo](https://ideone.com/aQ0jbM) for my claim. – Turing85 Jun 06 '23 at 20:36
  • Does this answer your question? [Get generic type of class at runtime](https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime) – Gastón Schabas Jun 06 '23 at 20:51
  • You need something like [`TypeToken`](https://guava.dev/typetoken) to do anything like this. – Louis Wasserman Jun 06 '23 at 20:59
  • Please provide enough code so others can better understand or reproduce the problem. – Community Jun 07 '23 at 15:09

1 Answers1

0

First, ParameterizedClass<MyClass>.class does not compile …

But let's assume it would …

Then you would encounter the surprising fact that

ParameterizedClass<MyClass>.class.equals( ParameterizedClass<String>.class )

is always true. In fact, even

ParameterizedClass<MyClass>.class == ParameterizedClass<String>.class

would be always true.

This means that you can just use ParameterizedClass.class to get the Classobject for your class – and that compiles …

The reason for that the TypeParameter will be 'erased' during/after compilation. It is not part of the code in the '.class' file.

tquadrat
  • 3,033
  • 1
  • 16
  • 29