首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >反射:在字符串中实例化和抛出来自类名的异常

反射:在字符串中实例化和抛出来自类名的异常
EN

Stack Overflow用户
提问于 2015-10-20 12:21:01
回答 1查看 1.6K关注 0票数 1

我在Spring项目中使用java创建一个通用的ItemProcessor。目前,我一直在研究如何从类中抛出异常,该类的名称作为此ItemProcessor的参数传递。

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

下面是代码的示例,???是我被困在其中的地方:

代码语言:javascript
运行
复制
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力学“是基于异常的类名。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-22 07:37:01

我通过显式指定Class对象扩展Exception找到了一个可行的解决方案。然后,我可以抛出它,而不需要声明该类的新对象。

代码语言:javascript
运行
复制
// 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 }));
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33236547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档