關於java.lang.reflect.InvocationTargetException


  今天遇到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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM