java - 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
解决方案
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).
推荐阅读
- python - numpy 矩阵中的 Lambda 函数
- python - 如何更改 Jinja 中子模板的背景颜色?
- reactjs - 我在本机反应中不断收到此导航错误
- java - 尝试在空对象引用上调用虚拟方法“void androidx.recyclerview.widget.RecyclerView.removeViewAt(int)”
- php - 根据选定的 div 进行下拉选择(使用 jQuery)
- php - 是否有一个功能可以让您知道您来自网站的哪个页面?
- markdown - 使用 jekyll 的“包含”和备注
- python - 使用 QProcess 运行 python 脚本并显示到文本中实时编辑结果
- python - Dash Plotly 中的向下钻取图表操作。触发下钻时如何更新下拉菜单(图表对象已更改)
- r - 在 R 中按日期序列和 id 变量聚合