Javareflection和检查exception
我有一个方法,我想通过反思来调用。 该方法对其参数进行了一些不同的检查,并且可以抛出NullPointer和IllegalArgumentexception。
通过Reflection调用方法也会抛出需要捕获的IllegalArgument和NullPointerexception。 有没有办法确定exception是由reflectionInvoke方法还是由方法本身引起的?
如果方法本身引发了exception,那么它将被包装在InvocationTargetException中 。
您的代码可能如下所示
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 } }
在回答原始问题时,exception中的堆栈跟踪会有所不同。
作为替代方案,您可以让函数捕获这些exception并将它们重新抛出为方法(或类)特定exception。