英文:
unchecked call to getDeclaredConstructor(Class
问题
Class c1 = Class.forName(theName)
return (CalculationFunction) c1.getDeclaredConstructor().newInstance();
但是我收到了这个警告:
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
答案1
得分: 1
`java.lang.Class`类是通用的,因此您需要对其进行参数化。因为您是根据类的名称进行操作,所以在编译时无法'知道'它是什么,因此实际上无法将其放入类型中。请尝试以下代码:
Class<?> c1 = Class.forName(theName);
return (CalculationFunction) c1.getDeclaredConstructor().newInstance();
请注意,除非将构造函数标记为可访问,否则此代码实际上不起作用,除非无参数构造函数是公共的,在这种情况下'getConstructor'更具惯性。上述代码要么毫无意义,要么有错误。
我认为您想要的更接近以下方式:
Class<?> c1 = Class.forName(theName);
Constructor<?> ctr = c1.getDeclaredConstructor();
ctr.setAccessible(true);
return (CalculationFunction) ctr.newInstance();
或者:
Class<?> c1 = Class.forName(theName);
return (CalculationFunction) c1.getConstructor().newInstance();
`j.l.Class`是通用的,要求您添加一些内容,否则会收到警告,但由于您不知道类型,而且已经进行了类型转换,通用性并没有太多作用;因此,`<?>` 将是合适的(而且您不能在那里放置其他任何内容,否则会收到更多警告)。
英文:
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).
答案2
得分: 0
你可以使用 Class<?> 来避免这个错误。
英文:
You can use Class<?> to avoid this error.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论