Get generic type of java.util.List

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

I have;

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

Is

14条回答
  •  感情败类
    2020-11-22 02:30

    At runtime, no, you can't.

    However via reflection the type parameters are accessible. Try

    for(Field field : this.getDeclaredFields()) {
        System.out.println(field.getGenericType())
    }
    

    The method getGenericType() returns a Type object. In this case, it will be an instance of ParametrizedType, which in turn has methods getRawType() (which will contain List.class, in this case) and getActualTypeArguments(), which will return an array (in this case, of length one, containing either String.class or Integer.class).

提交回复
热议问题