Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: unchecked call to getConstructor(java.lang.Class<?>...)

I am using reflection to construct a class (ConfigBuilder) that takes a File as argument:

Class myClassType = Class.forName(className);
Class[] types = new Class[] { File.class };
Constructor cons = myClassType.getConstructor(types);
Object[] constructorArgs = new Object[] { myFile };
cb = (ConfigBuilder) cons.newInstance(constructorArgs);

but I get this warning:

warning: [unchecked] unchecked call to getConstructor(java.lang.Class<?>...) as a member of the raw type java.lang.Class
Constructor cons = myClassType.getConstructor(types);

Obviously, it seems that getConstructor expects a generic type so I tried something like:

Class<?>[] types = new Class<?>[] { File.class };

but I get the same warning message

Any idea ?

David

like image 695
dm76 Avatar asked Feb 10 '10 17:02

dm76


2 Answers

The warning actually refers to myClassType. You need to parameterize it (and the cons) as well.

Class<?> myClassType = Class.forName(className);
Class<?>[] types = new Class[] { File.class };
Constructor<?> cons = myClassType.getConstructor(types);
like image 73
BalusC Avatar answered Nov 08 '22 19:11

BalusC


Firstly this is just a warning and should not cause you undue alarm when working with reflection and types that are unknown at compile time. The virtue of generics is stronger compile time type checking and all that goes out the window once you call Class.forName(className).

However if you are like most people (including me) then you probably want to get rid of the warning so that it does not continue to draw you attention unnecessarily. To do that you can parameterize the constructor variable cons:

Class<?> myClassType = Class.forName(className);
Class<?>[] types = new Class[] { File.class };
Constructor<?> cons = myClassType.getConstructor(types);
like image 31
Tendayi Mawushe Avatar answered Nov 08 '22 20:11

Tendayi Mawushe