java反射:避免警告unchecked调用getConstructor(Class ...)作为原始类型的成员Class(java reflection :Avoid warning unchec

编程入门 行业动态 更新时间:2024-10-27 14:33:24
java反射:避免警告unchecked调用getConstructor(Class <?> ...)作为原始类型的成员Class(java reflection :Avoid warning unchecked call to getConstructor(Class<?>…) as a member of the raw type Class)

我看过这篇文章

java:unchecked调用getConstructor(java.lang.Class <?> ...)

for (Map.Entry<String, Class> entry : connectionRepository.entrySet()) { if (/*someconditionhere*/) { try { cwsConnection = (CWSConnection)entry.getValue().getConstructor().newInstance(); break; } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { logger.error("Could not Create instance of CWSConnection for site version:\"{}\" Error:\"{}\"", entry.getKey(), e.getMessage(), e); } } }

编译这段代码时,我收到警告

警告:[unchecked] unchecked调用getConstructor(Class ...)作为原始类型Class的成员

我只想得到CWSConnection的默认构造函数,因此,我不应该将任何参数传递给getConstructor(Class ...)方法。 有没有更好的方法来获得默认的构造函数(没有参数的那个)

(我知道@SupressWarning注释会抑制此警告。)

I have read this post

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

for (Map.Entry<String, Class> entry : connectionRepository.entrySet()) { if (/*someconditionhere*/) { try { cwsConnection = (CWSConnection)entry.getValue().getConstructor().newInstance(); break; } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { logger.error("Could not Create instance of CWSConnection for site version:\"{}\" Error:\"{}\"", entry.getKey(), e.getMessage(), e); } } }

While compiling this piece of code I am getting a warning

warning: [unchecked] unchecked call to getConstructor(Class...) as a member of the raw type Class

I just wanted to get the default constructor of CWSConnection, therefore, I should not pass any parameters to getConstructor(Class...) method. Is there any better approach to get the default constructor(The one without arguments)

(I know @SupressWarning annotation will suppress this warning.)

最满意答案

只需将您的循环声明更改为

for (Map.Entry<String, Class<?>> entry : connectionRepository.entrySet()) {

你有这个错误,因为你使用参数化的Class作为原始类型。 在这里你可以阅读有关泛型和通配符 。 您可以使用Class<?>并避免此错误。 但是转换为CWSConnection仍然是必需的。 您可以通过拥有Map<String, Class<CWSConnection>>而不是Map<String, Class<?>>来避免它。

Just change your loop declaration to

for (Map.Entry<String, Class<?>> entry : connectionRepository.entrySet()) {

You've got this error because you use parametrised Class as a raw type. Here you can read about generics and wildcards. You can use Class<?> and avoid this error. But cast to CWSConnection is still required. You can avoid it by owning a Map<String, Class<CWSConnection>> instead of Map<String, Class<?>>.

更多推荐

本文发布于:2023-07-23 02:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   原始   成员   类型   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!