首页 > 解决方案 > unchecked call to getDeclaredConstructor(Class

问题描述

I have this piece of code

Class c1 = Class.forName(theName)
return (CalculationFunction) c1.getDeclaredConstructor().newInstance();

but I have this warn:

unchecked call to getDeclaredConstructor(Class

标签: java

解决方案


The java.lang.Class class is generified, so you need to parameterize it. Because you're going by the name of a class, there's no way to 'know' at compile time what it is, so it is not actually possibee to put in a type. Try this:

Class<?> c1 = Class.forName(theName);
return (CalculationFunction) c1.getDeclaredConstructor().newInstance();

note that this code doesn't actually work out unless you mark the constructor as accessible, unless the no-args constructor is public, in which case 'getConstructor' is more idiomatic. The above code is either uselessly obtuse, or buggy.

I think you intend something more along the lines of:

Class<?> c1 = Class.forName(theName);
Constructor<?> ctr = c1.getDeclaredConstructor();
ctr.setAccessible(true);
return (CalculationFunction) ctr.newInstance();

or:

Class<?> c1 = Class.forName(theName);
return (CalculationFunction) c1.getConstructor().newInstance();

j.l.Class, being generified, demands you add something or you get a warning, but because you don't know, and you're already casting, the generics isn't adding much; hence, <?> will be fine (and not that you can put anything else there without getting more warnings).


推荐阅读