I am trying to learn the difference between getGenericParameterTypes and getParameterTypes methods. I know that one returns Class[] and the other Type[]. But what is ther real difference?
Considering methods:
public void method1(T arg1)
public void method2(String arg2)
What would I get when invoking each of the get methods over each of the example methods?
I can’t exactly tell you what you would get, but one difference is that for method 2 you can tell the parameter type is
Class<String>whereas for method 1 you’d just know there’s a parameter namedT, but you don’t know the exact type except the class whereTis declared would have been subclassed with a concrete class forT.Example:
For
fooyou’d not be able to get the type ofTat runtime (you’d not know it’sBaz) nor at compile time. Forbaryou’d be able to get the type forTsince it is already known at compile time.Another difference when looking at the code:
Calling
getGenericParameterTypes()on method 1 should return theTtype, calling it for method 2 should returnClass<String>. However, if you callgetTypeParameters()you’d get theTtype for method 1 but a zero-length array for method 2.Edit: since
getParameterTypes()was meant instead ofgetTypeParameters()here’s the difference I can see from the code:For method 2 there would be no difference, since if no Generics are used in the signature,
getGenericParameterTypes()actually callsgetParameterTypes(). For method 1getGenericParameterTypes()would return aParameterizedTypethat states the parameter has nameTwhereasgetParameterTypes()would return the required base class of the type, e.g.Class<Object>for<T>orClass<Number>for<T extends Number>.