我看过这篇文章
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<?>>.
更多推荐
发布评论