Get generic type of java.util.List

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

I have;

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

Is

14条回答
  •  旧巷少年郎
    2020-11-22 02:36

    If those are actually fields of a certain class, then you can get them with a little help of reflection:

    package test;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.ParameterizedType;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
    
        List stringList = new ArrayList();
        List integerList = new ArrayList();
    
        public static void main(String... args) throws Exception {
            Field stringListField = Test.class.getDeclaredField("stringList");
            ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
            Class stringListClass = (Class) stringListType.getActualTypeArguments()[0];
            System.out.println(stringListClass); // class java.lang.String.
    
            Field integerListField = Test.class.getDeclaredField("integerList");
            ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType();
            Class integerListClass = (Class) integerListType.getActualTypeArguments()[0];
            System.out.println(integerListClass); // class java.lang.Integer.
        }
    }
    

    You can also do that for parameter types and return type of methods.

    But if they're inside the same scope of the class/method where you need to know about them, then there's no point of knowing them, because you already have declared them yourself.

提交回复
热议问题