dm76
dm76

Reputation: 4240

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

Upvotes: 18

Views: 9431

Answers (2)

BalusC
BalusC

Reputation: 1108712

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);

Upvotes: 26

Tendayi Mawushe
Tendayi Mawushe

Reputation: 26118

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);

Upvotes: 10

Related Questions