Java 反射和检查异常

发布于 2024-12-29 17:03:47 字数 182 浏览 2 评论 0原文

我有一个我想通过反射调用的方法。 该方法对其参数进行一些各种检查,并可能引发 NullPointer 和 IllegalArgument 异常。

通过Reflection调用该方法也会抛出IllegalArgument和NullPointer异常,需要捕获这些异常。有没有办法判断异常是反射Invoke方法引起的,还是方法本身引起的?

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.

Calling the method via Reflection also can throw IllegalArgument and NullPointer exceptions which need to be caught. Is there a way to determine whether the exception is caused by the reflection Invoke method, or by the method itself?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

星星的轨迹 2025-01-05 17:03:47

如果方法本身抛出异常,那么它将被包装在 InitationTargetException 中

你的代码可能看起来像这样

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

If the method itself threw an exception, then it would be wrapped in a 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
     }
}
安穩 2025-01-05 17:03:47

为了回答原来的问题,异常中的堆栈跟踪会有所不同。

作为替代方案,您可以让函数捕获这些异常并将它们作为方法(或类)特定异常重新抛出。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文