背景
前段时间发现了一个小问题,这里分享一下,希望能够帮到有需要的小伙伴
定位过程
java.lang.reflect.Method#invoke,由于invoke方法里抛了异常我们调用的时候一般都会捕获一下。
如果invoke调用的方法报错了,我们又想得到具体的错误信息怎么办呢?是不是首先想到java.lang.Throwable#getMessage,一顿操作后发现拿不到错误信息。查看源码发现invoke抛了三个异常
/**
* @throws IllegalAccessException if this {@code Method} object
* is enforcing Java language access control and the underlying
* method is inaccessible.
* @throws IllegalArgumentException if the method is an
* instance method and the specified object argument
* is not an instance of the class or interface
* declaring the underlying method (or of a subclass
* or implementor thereof); if the number of actual
* and formal parameters differ; if an unwrapping
* conversion for primitive arguments fails; or if,
* after possible unwrapping, a parameter value
* cannot be converted to the corresponding formal
* parameter type by a method invocation conversion.
* @throws InvocationTargetException if the underlying method
* throws an exception.
* @throws NullPointerException if the specified object is null
* and the method is an instance method.
* @throws ExceptionInInitializerError if the initialization
* provoked by this method fails.
*/
@CallerSensitive
public Object invoke(Object obj, Object... args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, obj, modifiers);
}
}
// read volatile
MethodAccessor ma = methodAccessor;
if (ma == null) {
ma = acquireMethodAccessor();
}
return ma.invoke(obj, args);
}
IllegalAccessException:当应用程序尝试以反射方式创建实例(而不是数组),设置或获取字段或调用方法时,但当前执行的方法无权访问指定类,字段,方法或构造函数,抛出IllegalAccessException。
IllegalArgumentException:被抛出以指示方法已传递了非法或不适当的参数。
InvocationTargetException :是一个已检查的异常,通过被调用的方法或者构造函数抛出(InvocationTargetException异常由Method.invoke(obj, args…)方法抛出。当被调用的方法的内部抛出了异常而没有被捕获时,将由此异常接收!)
由此可得知方法内部的异常信息被InvocationTargetException抛出,可利用此异常获取具体异常信息。
debug如下图:
获取message方法:
官方推荐的是java.lang.reflect.InvocationTargetException#getCause
ending。。。。。。。。。