您的位置:首页 > 编程语言 > Java开发

关于java.lang.reflect.InvocationTargetException

2016-05-15 12:27 381 查看
  今天遇到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[/code] 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: