简体   繁体   English

Java反射和检查异常

[英]Java reflection and checked exceptions

I have a method which I would like to call via reflection. 我有一个方法,我想通过反思来调用。 The method does some various checks on its arguments and can throw NullPointer and IllegalArgument exceptions. 该方法对其参数进行了一些不同的检查,并且可以抛出NullPointer和IllegalArgument异常。

Calling the method via Reflection also can throw IllegalArgument and NullPointer exceptions which need to be caught. 通过Reflection调用方法也会抛出需要捕获的IllegalArgument和NullPointer异常。 Is there a way to determine whether the exception is caused by the reflection Invoke method, or by the method itself? 有没有办法确定异常是由反射Invoke方法还是由方法本身引起的?

If the method itself threw an exception, then it would be wrapped in a InvocationTargetException . 如果方法本身引发了异常,那么它将被包装在InvocationTargetException中

Your code could look like this 您的代码可能如下所示

try
{
     method . invoke ( args ) ;
}
catch ( IllegalArgumentException cause )
{
     // reflection exception
}
catch ( NullPointerException cause )
{
     // reflection exception
}
catch ( InvocationTargetException cause )
{
     try
     {
           throw cause . getCause ( ) ;
     }
     catch ( IllegalArgumentException c )
     {
           // method exception
     }
     catch ( NullPointerException c )
     {
            //method exception
     }
}

In answer to the original question, the stack traces in the exceptions would be different. 在回答原始问题时,异常中的堆栈跟踪会有所不同。

As an alternative you could have the function catch these exceptions and rethrow them as method (or class) specific exceptions. 作为替代方案,您可以让函数捕获这些异常并将它们重新抛出为方法(或类)特定异常。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM