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

南笙酒味 提交于 2019-12-28 19:36:46

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2238818/java-unchecked-call-to-getconstructorjava-lang-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!