Reputation: 9319
I know how to access generic types of fields using reflection: Just check if field.getGenericType() instanceof ParameterizedType
.
But how can one check the same for an arbitrary object, not knowing where it was declared?
Upvotes: 2
Views: 216
Reputation: 4571
Objects do not store generic information per se, so the bytecode generated for new ArrayList<Integer>()
is exactly the same as the one for new ArrayList<String>()
. I mean exactly. This is what is called type erasure of Java generics. They are just desugared to new ArrayList()
.
But, in almost all other situations, type parameters are retained, like field/parameter/return type declarations. One of the cases that is retained and not erased is the super class of a class. So if you create a class that extends ArrayList<String>
you can access that information at runtime.
But this seems overkill, doesn't it? A new class that extends ArrayList<String>
and another one that extends ArrayList<String>
, etc. seems impractical. Anonymous inner classes can make this much easier. So, if you want to keep the generic information, you just do new ArrayList<String>() {}
instead of new ArrayList<String>()
. You can call getClass().getGenericSuperclass()
on the created object to get the generic info.
Upvotes: 2
Reputation: 122364
Generics apply to variable declarations, method return types, etc., not objects per-se. You can determine whether the Class
of a particular object uses generics via myObj.getClass().getTypeParameters()
but you can't determine what values of those type parameters the specific object instance was created with.
Upvotes: 2