Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of Class<?>#getTypeParameters()?

With a given java.lang.reflect.Method.

I can call,

final Class<?> returnType = method.getReturnType();

But when I tried to call getTypeParameters() with following statement,

final TypeVariable<Class<?>>[] typeParameters = returnType.getTypeParameters();

I got a compiler error.

required: java.lang.reflect.TypeVariable<java.lang.Class<?>>[]
found:    java.lang.reflect.TypeVariable<java.lang.Class<capture#1 of ?>>[]

What's wrong this statement? I just followed apidocs.

like image 448
Jin Kwon Avatar asked Dec 04 '25 06:12

Jin Kwon


2 Answers

the code is attempting to perform a safe operation.

Helper method needs to be created so that the wildcard can be captured through type inference. compiler is not able to confirm the type of object that is being inserted into the list, and an error is produced. When this type of error occurs it typically means that the compiler believes that you are assigning the wrong type to a variable. Generics were added to the Java language for this reason — to enforce type safety at compile time.

here is the java doc refrence that explains the same.

http://docs.oracle.com/javase/tutorial/java/generics/capture.html

while this will work

final TypeVariable<?>[] typeParameters =returnType.getTypeParameters();
like image 109
ManMohan Vyas Avatar answered Dec 05 '25 22:12

ManMohan Vyas


You should try

final Class<?> returnType = method.getReturnType();
final TypeVariable<?>[] typeParameters =  returnType.getTypeParameters();  
if (types.length > 0){  
   // do something with every type...
}
like image 24
Cristian Meneses Avatar answered Dec 05 '25 23:12

Cristian Meneses