今天遇到java.lang.reflect.InvocationTargetException错误,卡了好一会儿,报错代码

  

try { 
            Class<?> c= Class.forName("com.csdhsm.chat.server.handler." + handlerName); 
            Class<?>[] arg=new Class[]{SocketRequest.class,SocketResponse.class}; 
            Method method=c.getMethod(action,arg);
            Logger.getLogger(Logger.class).info("实例化处理器" + handlerName);
            method.invoke(c.newInstance(), new Object[]{request,response}); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 

  错误锁定在 method.invoke(c.newInstance(), new Object[]{request,response}); 这句话,我一直是以为反射出了什么错,后来google之后才发现是Method 这个方法里面出了错误,如果想要看到里面的错误,需要这样做  

try {
            Method method = obj.getClass().getMethod(methodName);
            method.invoke(obj);
        } catch(NoSuchMethodException e) {
            throw new RequestNotFoundException(
                    "无法找到方法:" + methodName, e);
        } catch(InvocationTargetException e) {
            Throwable t = e.getCause();
            t.printStackTrace();
            throw new ObjectFactoryException(t);
        } catch(Exception e) {
            e.printStackTrace();
            throw new ObjectFactoryException(e);
        }
重点在Throwable t = e.getCause(); 这句话。

参考链接 http://www.oschina.net/question/86510_14830
 posted on 2016-05-15 12:27  韩思明  阅读(14871)  评论(0编辑  收藏  举报