Java 反射和检查异常
我有一个我想通过反射调用的方法。 该方法对其参数进行一些各种检查,并可能引发 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果方法本身抛出异常,那么它将被包装在 InitationTargetException 中。
你的代码可能看起来像这样
If the method itself threw an exception, then it would be wrapped in a InvocationTargetException.
Your code could look like this
为了回答原来的问题,异常中的堆栈跟踪会有所不同。
作为替代方案,您可以让函数捕获这些异常并将它们作为方法(或类)特定异常重新抛出。
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.