简体   繁体   中英

How to identify if a java method is generic using reflection?

How do I check if getQueue() in the sample code is generic using reflection?. One way is to go through the argument types and return type and check if they are instance of TypeVariable . I'm looking for something simpler.

Class SomeClass {
 <V> Queue<V> getQueue();
}

You do not need to find a method's argument types or return type to identify if has type parameters, because the class Method has a method getTypeParameters returning an array of the type parameters.

Here is an example showing the use of this method. I have also shown the use of 2 other methods here, since the terminology is incredibly confusing.

public class SomeClass {

    <V, U> Queue<V> someMethod(String str, int a, List<U> list) {
        return null;
    }

    public static void main(String[] args) throws Exception {
        Method method = SomeClass.class.getDeclaredMethod("someMethod", String.class, int.class, List.class);

        TypeVariable<Method>[] typeParameters = method.getTypeParameters();
        System.out.println(typeParameters.length);                          // Prints "2"
        System.out.println(typeParameters[0].getName());                    // Prints "V"

        Class<?>[] parameterTypes = method.getParameterTypes();
        System.out.println(Arrays.toString(parameterTypes));                // Prints [class java.lang.String, int, interface java.util.List]

        Type[] genericParameterTypes = method.getGenericParameterTypes();
        System.out.println(genericParameterTypes[2].getTypeName());         // Prints java.util.List<U>
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM