I\'d like to get the generic type of a collection, using reflection, at runtime.
Code (JAVA):
Field collectionObject = object.getClass().getDeclaredF
You can absolutely do what you want. Type erasure means you can't inspect an instance of a collection for its generic type, but you can certainly inspect a field for its generic type.
class Thing {
List foo;
}
Field f = Thing.class.getDeclaredField("foo");
if( Collection.class.isAssignableFrom( f.getType() ) {
Type t = f.getGenericType();
if( t instanceof ParameterizedType ) {
Class genericType = (Class)((ParameterizedType)t).getActualTypeArguments()[0];
if( Persistable.class.isAssignableFrom( genericType ) )
return true;
}
}
There's a lot of things which can go wrong here, for example, if you have
Class Thing {
List foo;
}
then the above won't work.