项目中遇到的反射异常

前两天项目中遇到个问题,使用httpclient跨系统调用接口前创建对象的时候,调用设置http状态参数的方法,一直过不去,最可恨的是控制台 和日志都没有抛出错误信息,于是 debug进去跟了下代码,发现进到了反射异常的方法里,传进来的参数target是空,那么问题来了。首先为什么会出现反射异常,其次为什么方法内出现运行异常,但是这个异常却没有被外部捕获。  为了研究这两个问题首先看了下反射的定义

反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

看了下JDK的API文档关于method.invoke的注释说明其中,InvocationTargetException,就是用来解决你这个问题的:

InvocationTargetException - if the underlying method throws an exception.

InvocationTargetException
InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor

public Throwable getTargetException())
Get the thrown target exception.
This method predates the general-purpose exception chaining facility. The Throwable.getCause() method is now the preferred means of obtaining this information.

public Throwable getCause())

Returns the cause of this exception (the thrown target exception, which may be null).

这就是异常没被外部捕获的原因。

再来看下为什么会产生反射异常。

因为反射是在运行期间才知道名字对象的方法,反射要获得对应类 的访问修饰符,成员 方法构造方法以及超类信息。

所以 被反射的方法所在的类的关键字,全局变量,日志都要注意,以免造成反射的 错误导致方法无法调用。尤其是要调用的是

内部抽象类更要注意。

猜你喜欢

转载自blog.csdn.net/Nryana0/article/details/80004510