getting type of element in a List in which List is the return type of method in java

前端 未结 1 1139
眼角桃花
眼角桃花 2021-01-21 04:19

I got every methods in my package using reflections and then based on the return type of every method, I want to do some operations. But unfortunately I had a problem with coll

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 05:07

    You can use getGenericReturnType which returns a Type rather than a Class, and allows you to get at all the type arguments etc. Short but complete example:

    import java.lang.reflect.*;
    import java.util.*;
    
    public class Test {
    
        public static void main(String [] args) {
            for (Method method : Test.class.getMethods()) {
                System.out.println(method.getName());
                Type type = method.getGenericReturnType();
                System.out.println("Return type: " + type.getTypeName());
                if (type instanceof ParameterizedType)
                {
                    ParameterizedType pt = (ParameterizedType) type;
                    System.out.println("Parameterized: " + pt.getRawType());
                    for (Type arg : pt.getActualTypeArguments())
                    {
                        System.out.println("  " + arg);
                    }
                }
            }
        }
    
        public static List getNumbers() {
            return null;
        }
    
        public static List getStrings() {
            return null;
        }
    }
    

    Output includes:

    getStrings
    Return type: java.util.List
    Parameterized: interface java.util.List
      class java.lang.String
    getNumbers
    Return type: java.util.List
    Parameterized: interface java.util.List
      class java.lang.Integer
    

    0 讨论(0)
提交回复
热议问题