Java反射和检查异常 [英] Java reflection and checked exceptions

查看:153
本文介绍了Java反射和检查异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,我想通过反思来调用。
该方法对其参数执行一些各种检查,并可以抛出NullPointer和IllegalArgument异常。



通过Reflection调用该方法也可以抛出需要的IllegalArgument和NullPointer异常被抓住有没有办法确定异常是由反射Invoke方法引起的还是由方法本身引起?

解决方案

如果方法本身抛出一个异常,那么它将被包装在一个 InvocationTargetException < a>。



您的代码可能如下

  try 
{
方法。调用(args);
}
catch(IllegalArgumentException cause)
{
//反射异常
}
catch(NullPointerException cause)
{
//反映异常
}
catch(InvocationTargetException cause)
{
try
{
throw cause。 getCause();
}
catch(IllegalArgumentException c)
{
//方法异常
}
catch(NullPointerException c)
{
//方法异常
}
}


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?

解决方案

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

这篇关于Java反射和检查异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆