java: java.lang.reflect.InvocationTargetException
时间: 2023-10-12 11:18:28 浏览: 126
java.lang.reflect.InvocationTargetException is a checked exception that occurs when a method is invoked with reflection, but the method itself throws an exception.
In other words, if a method invoked via reflection throws an exception, the exception is wrapped in an InvocationTargetException and thrown to the caller. This exception typically occurs when the invoked method throws a checked exception that is not declared in the method signature.
For example, consider the following code:
```
public class MyClass {
public void myMethod() throws IOException {
// some code that may throw an IOException
}
}
// ...
try {
MyClass myObj = new MyClass();
Method myMethod = MyClass.class.getMethod("myMethod");
myMethod.invoke(myObj);
} catch (InvocationTargetException e) {
// handle the wrapped exception here
System.out.println("Exception occurred: " + e.getCause());
}
```
If myMethod throws an IOException, it will be wrapped in an InvocationTargetException and thrown to the caller. The catch block can then extract the wrapped exception using the getCause() method and handle it appropriately.
阅读全文