Java的反射是好东西,很多框架都用到它,言归正传我说说遇到的问题:
method.invoke(....)
当method中有 类似以下代码时:
int i=1/0;//会有ArithmeticException
或者:
String str = null;
str.getLength();//会报NullPointException
以上种类的代码时候,当然我是故意这样的,方法内也没try catch,不是要讨论这种异常产生的原因,
那么method.invoke所在的try...catch,是捕获不到这类异常的。
这要怎么解决?
写Java 遇到一大痛点 反射调用方法,方法内出现运行时异常,外部无法捕获!
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
5条回答 默认 最新
破小孩儿 2016-06-02 08:52关注请仔细看看JDK的API文档关于method.invoke的注释说明
public Object invoke(Object obj, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException "")
其中,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 constructorpublic 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).这根本不能算是痛点,学Java,必须有随时翻阅javadoc的习惯,无论是JDK的还是三方件的。理解javadoc比读完一本Java编程类书籍,对学习Java更有用。
评论 打赏 举报解决 2无用