Specifying generic collection type param at runtime (Java Reflection)

前端 未结 4 751
情书的邮戳
情书的邮戳 2021-01-06 02:40

I\'d like to get the generic type of a collection, using reflection, at runtime.

Code (JAVA):

Field collectionObject = object.getClass().getDeclaredF         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 03:41

    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.

提交回复
热议问题