2014-10-10 11 views
0

我想動態加載一個類並從我的Servlet中調用它的一個方法。如何在動態調用方法時在servlet中顯示輸出

在我的servlet我有以下代碼:

PrintWriter out = response.getWriter(); 

try { 
     Class<?> obj = Class.forName(myclassName);   
     Method method = obj.getClass().getMethod(myMethodName); 
     String returnValue = (String) method.invoke(obj, null); 
     out.println(returnValue); 

} 
catch(Exception e){} 

而在I類有:

public class StudentClass { 

    public String index() 
    { 
    return "This is From StudentClass"; 
    } 
} 

問題是,當我運行我的應用程序不會顯示任何內容。我期待得到This is From StudentClass作爲輸出,基本上index方法正在返回。

請問如何解決這個問題?

+0

你有什麼異常嗎?不要貪吃exceptio,嘗試在你的Exception塊中打印堆棧跟蹤? – 2014-10-10 11:28:28

+0

@ Juned Ahsan謝謝你的回覆。我沒有任何例外。在我的實際代碼中有'e.printStackTrace();'。 – 2014-10-10 11:30:14

回答

1

invoke用法是錯誤的:

Class<?> obj = Class.forName(myclassName); // this return a Class, not an instance 
Method method = obj.getClass().getMethod(myMethodName); 
String returnValue = (String) method.invoke(obj, null); 

正確使用會是這樣的:

Class<?> clazz = Class.forName(myclassName);   
Object obj = clazz.newInstance(); // this give you a StudentClass instance 
Method method = clazz.getMethod(myMethodName); 
String returnValue = (String) method.invoke(obj); 

又見Class.forName(String)Method.invoke(Object, Object...)this tutorial on reflection API

+0

非常感謝。它的工作現在完美。我現在將通讀教程。謝謝。 – 2014-10-10 11:43:04

相關問題