2014-03-03 74 views
0

我想在類中創建一個對象時使動態類中的方法名稱我想動態執行方法名稱下面是我的代碼。如何使類中的方法名稱動態化?

public static void ExecuteTest() throws Exception 
{ 
    for (int i = 1, j = 1; i < 2; i = i+1, j = j+1) {  
      FW_ReadExcelFile N = new FW_ReadExcelFile(); 
      FW_ReadExcelFile.setExcelSheetEnvValues(i,i); 
      //java.lang.String Flag2 = N.getTCExecuteFlag() ; 

      String Flag = "YES"; 
      String Flag21 = N.getTCExecuteFlag(); 


      if (Flag.equals(Flag21) ){ 
       String TCName = N.getTCName(); 
       FW_Report u = new FW_Report(); 
       u.TCName; // the FW_Report class has many methods and I want to call the method on my demand . 
      } 
+3

爲什麼你需要這樣做? – Teo

+1

你的代碼風格表明你已經足夠新到Java,你*真*不應該嘗試反射。 – chrylis

+0

我想要執行在本地excel表中有「是」的方法,而那些有「否」的方法應該被忽略。 –

回答

1

我想執行的方法名稱動態

使用Reflections in Java實現這一目標。

示例代碼:

 Class<?> name = Class.forName("ClassName"); 
     Object instance = name.newInstance(); 
     Method[] methods = name.getMethods(); 

     for (Method method : methods) { 
      if (method.getName().equals(N.getTCName())) { 
       // Match found. Invoke the method. call the method on my demand. 
       method.invoke(instance, null); 
       break; 
      } 
     } 

或者乾脆試試這個:

 // Get the method name at runtime 
     Method method = ClassName.class.getMethod(N.getTCName(), null); 
     method.invoke(new ClassName(), null); 
+0

FW_Report u = new FW_Report();已經加載FW_Report類?我不認爲我們需要做Class.forName(); FW_Report.class就足夠了。 – TheLostMind

+0

@WhoAmI:是的,這是真的。我們也可以加載它。 –

+0

@AnkurShanbhag:當你只需要Clazz.getMethod(...)時,在foreach循環中有什麼意義。 –

0

使用Java反射。

java.lang.reflect.Method method = u.getClass().getMethod("getReportName", param1.class, param2.class, ..); 

method.invoke(obj,/*param1*/,/*param2*/,....); 

getReportName是您想要調用的方法名稱的示例。請參考java反射。

相關問題