public class Test {
public static void main(String[] args) {
try {
Method method = Test.class.getDeclaredMethod("method", null);
Test test = new Test();
method.invoke(test, null);
} catch (NullPointerException e) {
System.out.println(1);
} catch (InvocationTargetException e) {
System.out.println(2);
} catch (Exception e) {
System.out.println(3);
}
}

public void method () {
throw new NullPointerException();
}
}java

解决方案 »

  1.   

    看一下java.lang.reflect.Method的invoke的方法的说明:
    @exception InvocationTargetException if the underlying method throws an exception.
    如果被调的方法抛出了异常,那么invoke就会抛出InvocationTargetException。
    so...
      

  2.   


    InvocationTargetException 在空指针前面抛出了具体的我查看下代码
      

  3.   

    你最后调用的是invoke函数    public Object invoke(Object obj, Object... args)
            throws IllegalAccessException, IllegalArgumentException,
               InvocationTargetException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass(1);                checkAccess(caller, clazz, obj, modifiers);
                }
            }
            MethodAccessor ma = methodAccessor;             // read volatile
            if (ma == null) {
                ma = acquireMethodAccessor();
            }
            return ma.invoke(obj, args);
        }它只能抛出InvocationTargetException跟另外2个异常,也就是你这个方法里不管抛出什么异常,它都会捕获到,然后再抛一个InvocationTargetException出来,这根楼主在它里边抛什么异常没有关系
      

  4.   


    InvocationTargetException 在空指针前面抛出了具体的我查看下代码
    嗯,明白了。多谢啦。那这样的话,在动态调用的时候是不是就没法捕获自己抛出的异常了?
      

  5.   


    异常被覆盖了,因为你执行invoke方法。methed里面方法抛出异常被invoke检测到 然以invoke就抛出自己的异常了,而不是method方法里的异常
      

  6.   

    已经有解决方法。结贴了。方法就是在自己抛出的异常中加入Message。然后
    e.getCause().getMessage() 就能获取到抛出的信息了。
      

  7.   


    InvocationTargetException 在空指针前面抛出了具体的我查看下代码
    嗯,明白了。多谢啦。那这样的话,在动态调用的时候是不是就没法捕获自己抛出的异常了?
    或者你可以直接在被调用的方法里捕获异常,而别往外抛异常