Java 反射 - 反射调用时的包装异常(InvocationTargetException)
反射调用时的包装异常1、基本介绍通过反射调用方法 → 方法内部抛异常 → 反射框架捕获并包装成 InvocationTargetException → 其getCause()才是真正的异常2、演示publicclassDemo{publicvoidproblematicMethod(){intresult10/0;}publicvoidcheckedExceptionMethod()throwsException{thrownewException(业务异常);}}try{Class?clazzClass.forName(com.reflection.Demo);Constructor?constructorclazz.getDeclaredConstructor();Objectinstanceconstructor.newInstance();Methodmethodclazz.getMethod(problematicMethod);method.invoke(instance);}catch(ClassNotFoundException|NoSuchMethodException|IllegalAccessException|InstantiationExceptione){e.printStackTrace();}catch(InvocationTargetExceptione){System.err.println(外层异常: e.getClass().getSimpleName());System.err.println(e.getMessage());System.err.println(真实原因: e.getCause());e.getCause().printStackTrace();}# 输出结果 外层异常: InvocationTargetException null 真实原因: java.lang.ArithmeticException: / by zero java.lang.ArithmeticException: / by zerotry{Class?clazzClass.forName(com.reflection.Demo);Constructor?constructorclazz.getDeclaredConstructor();Objectinstanceconstructor.newInstance();Methodmethodclazz.getMethod(checkedExceptionMethod);method.invoke(instance);}catch(ClassNotFoundException|NoSuchMethodException|IllegalAccessException|InstantiationExceptione){e.printStackTrace();}catch(InvocationTargetExceptione){System.err.println(外层异常: e.getClass().getSimpleName());System.err.println(e.getMessage());System.err.println(真实原因: e.getCause());e.getCause().printStackTrace();}# 输出结果 外层异常: InvocationTargetException null 真实原因: java.lang.Exception: 业务异常 java.lang.Exception: 业务异常