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
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With