简体   繁体   English

如何抛出通过反射创建的 Exception 类的实例?

[英]How do you throw an instance of an Exception class created through reflection?

I am trying to create a function that throws an exception based on the type that you pass in.我正在尝试创建一个函数,该函数根据您传入的类型引发异常。

private void myFunc(Class<?> exceptionType) {
   ...do some work...
   throw new exceptionOfTypeExceptionTypePassedIn(newMessage);
}

Can you do this?你能做这个吗?

First, the throw statement only works with reference expressions of Throwable or its subtypes.首先, throw语句仅适用于Throwable或其子类型的引用表达式。 Therefore, the expression you pass to your throw must have that type.因此,您传递给throw的表达式必须具有该类型。 You can achieve this, by providing a bound for the exceptionType parameter.您可以通过为exceptionType参数提供一个界限来实现这一点。

private void myFunc(Class<? extends Throwable> exceptionType) {

If you now want to restrict the type of Throwable subtype, you can do that too.如果您现在想限制Throwable子类型的类型,您也可以这样做。

If it's Exception , you'll need a throws declaration如果是Exception ,则需要throws声明

private void myFunc(Class<? extends Exception> exceptionType) throws Exception {

If it's RuntimeException , it won't如果是RuntimeException ,则不会

private void myFunc(Class<? extends RuntimeException> exceptionType) {

Depending on what you need, you might actually make the method generic.根据您的需要,您实际上可能使该方法通用。 It would then look like this然后它看起来像这样

private <T extends Throwable> void myFunc(Class<T> exceptionType) throws T {

As for the actual reflection logic, you are making the assumption that the corresponding type has an accessible constructor which accepts a String argument.至于实际的反射逻辑,您假设相应的类型有一个可访问的构造函数,它接受一个String参数。 If it doesn't, Java will throw all sorts of exceptions of its own.如果没有,Java 将抛出自己的各种异常。 You need to handle these.你需要处理这些。

A potential solution would look like this ( javadoc for Class#getConstructor , javadoc for Constructor#newInstance )一个潜在的解决方案看起来像这样( 的javadocClass#getConstructorjavadoc中Constructor#newInstance

private <T extends Throwable> void myFunc(Class<T> exceptionType) throws T {
    final String message = "some message";
    try {
        throw exceptionType.getConstructor(String.class).newInstance(message);
    } catch (InstantiationException e) {
        e.printStackTrace();
        // rethrow
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        // rethrow
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        // rethrow
    } catch (InvocationTargetException e) {
        e.printStackTrace();
        // rethrow
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
        // rethrow
    } catch (SecurityException e) {
        e.printStackTrace();
        // rethrow
    }
}

You can obviously collapse all those exception types into a multi-catch statement.显然,您可以将所有这些异常类型折叠到一个多捕获语句中。

Note that if the exception type you passed in was one of those mentioned in the existing catch statements, it will be swallowed, ie.请注意,如果您传入的异常类型是现有catch语句中提到的异常类型之一,它将被吞下,即。 not thrown.不扔。 You can also add all those in a throws declaration of its own.您还可以将所有这些添加到自己的throws声明中。

private static <T extends Throwable> void myFunc(Class<T> exceptionType) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, T {
    final String message = "some message";
    throw exceptionType.getConstructor(String.class).newInstance(message);
}

or rethrow the caught exceptions wrapped in a RuntimeException .或者重新抛出包裹在RuntimeException的捕获异常。

您可以在Class对象上使用newInstance方法。

Reflection is pretty messy.反射相当混乱。 The accepted answer works, but your code will be harder to follow.接受的答案有效,但您的代码将更难以遵循。 You're probably better off refactoring your code to avoid this situation.您最好重构代码以避免这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建第二个实例时抛出异常 - Throw exception when second instance is created 您如何从另一个类中调用另一个类中创建的类实例的方法? - How do you call the methods of a class instance that was created in another class, from another class? 如何对通过反射创建的对象进行类型转换以运行方法? - How do I typecast an object created through reflection to run a method? 反射-如何为使用反射创建实例的POJO类设置值 - Reflection - How to set values for the POJO Class whose instance is created using reflection 由类名创建的反射中的 ClassNotFound 异常 - ClassNotFound Exception in Reflection created by Class name 如何在不中断for循环的情况下引发异常? - How do you throw an Exception without breaking a for loop? 你如何在java中创建一个抛出异常的方法? - How do you create a method to throw an exception in java? 如何确保不能使用反射从 class 外部创建具有私有构造函数的 class 实例? - How to make sure instance of a class with a private constructor can not be created from outside of the class using Reflection? 你抛出什么样的异常? - What kind of Exception do you throw? 使用PowerMockito模拟通过反射创建的新实例 - Mock new instance created through reflection using PowerMockito
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM