I had to use reflection to instantiate a group of classes. With that all good, but reflection uses many exceptions and my method looks ugly.
What do good practices advise in these cases?
It is supposed to throw these exceptions and catch them in a high level class to be able to give clear information about the error, but if I'm going through 6 or 8 exceptions among all the methods and classes involved, the code will be horrible, chaotic and very horrible.
private Filter getFilterInstance(String path){
try {
return (Filter) Class.forName(path).getConstructor().newInstance();
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(FiltersBuilder.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
You can catch ReflectiveOperationException
It is the super type of:
Which means you just need to:
} catch (ReflectiveOperationException | SecurityException | IllegalArgumentException ex) {
Logger.getLogger(FiltersBuilder.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
Since SecurityException
& IllegalArgumentException
are actually Runtime Exceptions, you could:
} catch (ReflectiveOperationException ex) {
Logger.getLogger(FiltersBuilder.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
if you are OK with the RuntimeException
propagating to callers.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments