Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection and checked exceptions

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?

like image 527
Trasvi Avatar asked Jan 29 '12 00:01

Trasvi


People also ask

What are the checked and unchecked exceptions in Java?

A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.

What are the checked exceptions in Java?

A checked exception in Java represents a predictable, erroneous situation that can occur even if a software library is used as intended. For example, if a developer tries to access a file, the Java IO library forces them to deal with the checked FileNotFoundException.

Which exceptions are checked exceptions?

ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.


1 Answers

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
     }
}
like image 111
emory Avatar answered Nov 09 '22 21:11

emory