写Java 遇到一大痛点 反射调用方法,方法内出现运行时异常,外部无法捕获!

Java的反射是好东西,很多框架都用到它,言归正传我说说遇到的问题:
method.invoke(....)
当method中有 类似以下代码时:
int i=1/0;//会有ArithmeticException
或者:
String str = null;
str.getLength();//会报NullPointException
以上种类的代码时候,当然我是故意这样的,方法内也没try catch,不是要讨论这种异常产生的原因,
那么method.invoke所在的try...catch,是捕获不到这类异常的。
这要怎么解决?

请仔细看看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 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).

这根本不能算是痛点,学Java,必须有随时翻阅javadoc的习惯,无论是JDK的还是三方件的。理解javadoc比读完一本Java编程类书籍,对学习Java更有用。

直接抛出来给外层去catch

可以,但是method的具体代码是由程序员按照日常习惯编写,难道你会在每个方法里一开始就try...catch吗?我想有这个习惯的不多,而且这个是运行时异常,是不用显式try..catch的。

做个代理类专门负责处理异常

如果是你写的代码,被第三方调用执行抛出InvocationTargetException而苦恼的话,
比如讲spring的bean调用方法肯定是用到了反射,那么就会出现你的那种问题。
如果想要你的程序健壮并且解耦运行时异常处理的话,你可以在注入springbean之前就生成自己的代理bean,
那样你的代理逻辑将在spring代理的内层,也就是说你完全可以自己处理这些运行时异常,并且
可以选择哪里异常可以忽略,哪些异常可以抛出给spring。

这样的好处有很多,
比如为每个执行方法加入执行日志,便于追踪和效率记录等。
所以一个应用程序在组建架构时,就应该想到可能出现的业务场景和相应的处理原型。