Difference between getGenericParameterTypes and getParameterTypes

I'm trying to find out the difference between the getGenericParameterTypes and getParameterTypes . I know that one returns Class[] and the other Type[] . But what is the real difference?

Given the methods:

 public void method1(T arg1) public void method2(String arg2) 

What will I get when I call each of the get methods for each of the example methods?

+7
source share
2 answers

I can’t tell you exactly what you will get, but the one difference is that for method 2 you can specify the type of the parameter Class<String> , whereas for method 1 you just know there the parameter named T , but you don’t know the exact of type, except for the class in which T declared, would be subclassed by a concrete class for T

Example:

 class Foo<T> { public void method1( T arg1 ) { ... } } class Bar extends Foo<Baz> { ... } Foo<?> foo = new Foo<Baz>(); Bar bar = new Bar(); 

In foo you cannot get type T at runtime (you don't know its Baz ) or at compile time. For bar you can get a type for T , since it is already known at compile time.

Another difference when viewing the code:

The call to getGenericParameterTypes() in method 1 should return a type T , the caller for method 2 should return Class<String> . However, if you call getTypeParameters() , you will get a type T for method 1, but a zero-length array for method 2.

Edit: since instead of getTypeParameters() instead of getTypeParameters() was specified the difference that I see from the code:

There was no difference for method 2, since if Generics are not used in the signature, getGenericParameterTypes() does indeed call getParameterTypes() . For method 1, getGenericParameterTypes() will return ParameterizedType , which indicates that the parameter is named T , while getParameterTypes() returns the required base type class, for example. Class<Object> for <T> or Class<Number> for <T extends Number> .

+6
source

getGenericParameterTypes may return a different type of Type s. getParameterType is a "pre-dipid" reflection. This means that T will be considered java.lang.Object . Check out this example:

 public class Generics<T> { public void method1(T t) { } public static void main(String[] args) throws Exception { Method m = Generics.class.getMethod("method1", Object.class); for (Type t : m.getGenericParameterTypes()) { System.out.println("with GPT: " + t); } for (Type t : m.getParameterTypes()) { System.out.println("with PT: " + t); } } } 

Output:

 with GPT: T with PT: class java.lang.Object 
+5
source

All Articles