Get generic type of java.util.List

后端 未结 14 2530
广开言路
广开言路 2020-11-22 02:06

I have;

List stringList = new ArrayList();
List integerList = new ArrayList();

Is

14条回答
  •  没有蜡笔的小新
    2020-11-22 02:36

    import org.junit.Assert;
    import org.junit.Test;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.ParameterizedType;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    public class GenericTypeOfCollectionTest {
        public class FormBean {
        }
    
        public class MyClazz {
            private List list = new ArrayList();
        }
    
        @Test
        public void testName() throws Exception {
            Field[] fields = MyClazz.class.getFields();
            for (Field field : fields) {
                //1. Check if field is of Collection Type
                if (Collection.class.isAssignableFrom(field.getType())) {
                    //2. Get Generic type of your field
                    Class fieldGenericType = getFieldGenericType(field);
                    //3. Compare with 
                    Assert.assertTrue("List",
                      FormBean.class.isAssignableFrom(fieldGenericType));
                }
            }
        }
    
        //Returns generic type of any field
        public Class getFieldGenericType(Field field) {
            if (ParameterizedType.class.isAssignableFrom(field.getGenericType().getClass())) {
                ParameterizedType genericType =
                 (ParameterizedType) field.getGenericType();
                return ((Class)
                  (genericType.getActualTypeArguments()[0])).getSuperclass();
            }
            //Returns dummy Boolean Class to compare with ValueObject & FormBean
            return new Boolean(false).getClass();
        }
    }
    

提交回复
热议问题