0

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?

ayushgp
  • 4,045
  • 3
  • 29
  • 67

2 Answers2

2

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

kimcodes
  • 696
  • 1
  • 6
  • 16
1

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.

Jan Gassen
  • 2,938
  • 1
  • 21
  • 39