18

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

2 Answers 2

26

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This works great, just also adding that you can use Class<?> myClassType = SpecificClass.class; In my circumstance.
10

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.