Reputation: 1234
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();
}
Upvotes: 0
Views: 70
Reputation: 37645
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>
}
}
Upvotes: 1