Is there a way to check if an Object
is a generic and how many parameters does it take? I know that it is not possible to get the name of the class of these parameters due to type erasure but is it also not possible to get the above?

- 4,891
- 8
- 40
- 75
-
https://stackoverflow.com/a/339708/4467208 – Murat Karagöz Feb 01 '18 at 15:15
-
@MuratK. so how do I find this information? – ayushgp Feb 01 '18 at 15:16
-
I don't know, but that guy there is talking about the reflection api. So maybe look there? – Murat Karagöz Feb 01 '18 at 15:17
2 Answers
Only the java compiler knows about generic types, therefore after compilation time basically this knowledge is lost and your code has no clue about generic parameters being passed around.
Now that being said, this apparently does not happen (the loss of knowledge at runtime - type erasure) when you are implementing and instantiating an anonymous class. This is very well explained through an example in this article Using TypeTokens to retrieve generic parameters

- 736
- 1
- 6
- 16
If the class of the object itself is generic, you can simply check:
obj.getClass().getTypeParameters();
This should give you an array of all type parameters and at least also gives you the names of the type parameters. However I don't think that it provides details about the actual types being used.
Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order. Returns an array of length 0 if the underlying generic declaration declares no type variables.

- 3,406
- 2
- 26
- 44