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.)
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<?>>
.
The method
Class.newInstance()
calls the default constructor of the class. But I don't think this help you with the warnings, because your Class
is still a raw type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.