2017-08-10 58 views
1

我想了解反射如何工作,我無法找出問題所在。在第二個循環中,method.length不是從另一個程序中獲取方法。在硒中的java反射

以下是代碼:

public class DriverScript 
{ 

    public static ActionKeywords actionKeywords; 
    public static String sActionKeyword; 
    public static Method method[]; 

    public DriverScript() throws NoSuchMethodException, SecurityException 
    { 
     actionKeywords = new ActionKeywords(); 
     method = actionKeywords.getClass().getMethods(); 
    } 

    public static void main(String[] args) throws Exception 
    { 
     System.out.println(method); 
     String sPath = "C:\\Users\\mag6\\Desktop\\toolsqa.xlsx"; 
     ExcelUtils.setExcelFile(sPath, "Test Steps"); 

     for (int iRow = 1; iRow <= 9; iRow++) 
     { 
      sActionKeyword = ExcelUtils.getCellData(iRow, 3); 
      execute_Actions(); 
     } 
    } 

    private static void execute_Actions() throws Exception 
    { 
     for (int i = 0; i < 11; i++) 
     { 
      if (method[i].getName().equals(sActionKeyword)) 
      { 
       method[i].invoke(actionKeywords); 
       break; 
      } 
     } 
    } 
} 
+0

https://stackoverflow.com/questions/29250410/get-methods-using-java-reflection-class **指這個** – selvakumar

+0

沒有大膽的應在那裏。 –

回答

0

你是不是叫這樣的字段沒有初始化DriverScript構造。

嘗試將您的方法從靜態更改爲非靜態並從此處修復。

+0

我曾經調用DriverScript的構造函數。 method = actionKeywords.getClass()。getMethods();顯示空值.. – selvakumar

+0

以及我不知道'ActionKeywords'類有什麼方法可用,因爲你沒有發佈該代碼。我已經修復了你發佈的問題,請標記爲公認的 –

+0

公共靜態WebDriver驅動程序; public static void openBrowser()我的方法之一 – selvakumar

0
public class Test2 { 
     //Reflection in Keyword driven Framework 
    /** 
    * @authors Venkadesh,Selvakumar work name : Test 
    **/ 
    static Class Class1 = ActionKeywords.class; 
    static ActionKeywords Keywords = new ActionKeywords(); 
    public static void main(String[] args) throws Exception { 

     String sPath = "C:\\Users\\mag6\\Desktop\\toolsqa.xlsx"; 
     ExcelUtils.setExcelFile(sPath, "Test Steps"); 
     Method[] methods = Class1.getDeclaredMethods(); 

     for (int i = 1; i <= 9; i++) { 
      // This to get the value of column Action Keyword from the excel 
      String sActionKeyword = ExcelUtils.getCellData(i, 3); 
      for (int j = 1; j <= 9; j++) { 
       if (methods[j].getName().equals(sActionKeyword)) { 
        try { 

         methods[j].invoke(Keywords); 
        } catch (Exception e) { 
        } 

        System.out.println(methods[j]); 
       } 

      } 

     } 
    } 
} 

嘗試這個它的工作原理