我在Spring项目中使用java创建一个通用的ItemProcessor
。目前,我一直在研究如何从类中抛出异常,该类的名称作为此ItemProcessor
的参数传递。
在下面的代码中,我设法从String参数中获取实际的类,然后获得所需的构造函数(带有1个参数)。但是,当我想实例化(作为参数传递的类的)实际异常,然后抛出它时,我不知道如何声明这个异常的容器。
下面是代码的示例,???
是我被困在其中的地方:
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 {
}
编辑
我可能需要补充的一件事是,我需要用作为参数传递的确切类抛出异常,因为Spring批处理"Skip力学“是基于异常的类名。
发布于 2015-10-22 07:37:01
我通过显式指定Class
对象扩展Exception
找到了一个可行的解决方案。然后,我可以抛出它,而不需要声明该类的新对象。
// 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 }));
https://stackoverflow.com/questions/33236547
复制相似问题