Get generic type of java.util.List

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

I have;

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

Is

14条回答
  •  我在风中等你
    2020-11-22 02:36

    If you need to get the generic type of a returned type, I used this approach when I needed to find methods in a class which returned a Collection and then access their generic types:

    import java.lang.reflect.Method;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import java.util.Collection;
    import java.util.List;
    
    public class Test {
    
        public List test() {
            return null;
        }
    
        public static void main(String[] args) throws Exception {
    
            for (Method method : Test.class.getMethods()) {
                Class returnClass = method.getReturnType();
                if (Collection.class.isAssignableFrom(returnClass)) {
                    Type returnType = method.getGenericReturnType();
                    if (returnType instanceof ParameterizedType) {
                        ParameterizedType paramType = (ParameterizedType) returnType;
                        Type[] argTypes = paramType.getActualTypeArguments();
                        if (argTypes.length > 0) {
                            System.out.println("Generic type is " + argTypes[0]);
                        }
                    }
                }
            }
    
        }
    
    }
    

    This outputs:

    Generic type is class java.lang.String

提交回复
热议问题