mardi 20 octobre 2015

Reflect : Instantiate and throw exception from classname in string

I am using java Reflect in my Spring Batch project to create a generic ItemProcessor. I am currently stuck on how to throw an Exception from a class whose name is passed as an argument of this ItemProcessor.

In my code below, I manage to get the actual class from the String parameter, then get the needed constructor (with 1 argument). But when I want to instantiate the actual Exception (of the class passed as a parameter) and then throw it, I don't know how to declare the container of this exception.

Here's a sample of the code, the ??? are where I'm stuck :

String exceptionClass; // With getter/setter
String exceptionText;  // With getter/setter

Class<?> clazz;
Constructor<?> constructor;

try {
    // Get the Exception class
    clazz = Class.forName(exceptionClass);

    // Get the constructor of the Exception class with a String as a parameter
    constructor = clazz.getConstructor(String.class);

    // Instantiate the exception from the constructor, with parameters
    ??? exception = clazz.cast(constructor.newInstance(new Object[] { exceptionText }));

    // Throw this exception
    throw exception;

} finally {
}

EDIT

One thing I might need to add is that I need the exception to be thrown with the exact class which was passed as an argument, since Spring Batch "Skip Mechanics" are based on the exceptions' classname.





Aucun commentaire:

Enregistrer un commentaire