反映:实例化并从字符串中的类名抛出异常

Reflect : Instantiate and throw exception from classname in string

我正在使用 java Reflect in my Spring Batch project 来创建通用 ItemProcessor。我目前停留在如何从 class 中抛出异常,其名称作为此 ItemProcessor.

的参数传递

在我下面的代码中,我设法从 String 参数中获取实际的 class,然后获取所需的构造函数(带有 1 个参数)。但是当我想实例化实际的异常(作为参数传递的 class 的)然后抛出它时,我不知道如何声明这个异常的容器。

这是代码示例,??? 是我卡住的地方:

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 {
}

编辑

我可能需要添加的一件事是我需要使用作为参数传递的确切 class 抛出异常,因为 Spring 批处理 "Skip Mechanics" 是基于关于例外的 classname.

我通过明确指定 Class 对象扩展 Exception 找到了一个可行的解决方案。然后我可以抛出它而无需声明此 class.

的新对象
// Get class of the exception (with explicit "extends Exception")
Class<? extends Exception>clazz = (Class<? extends Exception>) Class.forName(exceptionClass);

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

// Instantiate and throw immediatly the new Exception
throw clazz.cast(constructor.newInstance(new Object[] { exceptionText }));