Java reflection and checked exceptions

2019-04-30 18:50发布

I have a method which I would like to call via reflection. The method does some various checks on its arguments and can throw NullPointer and IllegalArgument exceptions.

Calling the method via Reflection also can throw IllegalArgument and NullPointer exceptions which need to be caught. Is there a way to determine whether the exception is caused by the reflection Invoke method, or by the method itself?

2条回答
We Are One
2楼-- · 2019-04-30 19:17

If the method itself threw an exception, then it would be wrapped in a InvocationTargetException.

Your code could look like this

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
     }
}
查看更多
做个烂人
3楼-- · 2019-04-30 19:25

In answer to the original question, the stack traces in the exceptions would be different.

As an alternative you could have the function catch these exceptions and rethrow them as method (or class) specific exceptions.

查看更多
登录 后发表回答