【问题标题】:How do i invoke a method that's in another class from main class java我如何从主类java调用另一个类中的方法
【发布时间】:2016-08-13 17:31:52
【问题描述】:

我是 Java 新手。

我正在使用 Selenium。我有threeATSmoke 这是主要类。我在 Excel 工作表中的所有方法名称都在其他两个类ProfileSchedule 中。现在我使用POI library 来获取单元格值(即方法名称)。

这里我卡住了,如何在另一个类 Profile 中调用这些方法(edit_contact_info)。如果他们在同一个班级。我可以使用相同的类名来引用。但不能为其他课程做。

另外,还有一个名为 ATTestDriver 的类,我拥有所有实用方法,例如选择 webdriver、浏览器等。

public class ATSmoke {

    public static void main(String[] args){
        Profile profileDriver = new Profile(Browsers.CHROME);
        XSSFWorkbook srcBook = null;
        try {
            srcBook = new XSSFWorkbook("./TestData/Testcase_data_v1.xlsx");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        XSSFSheet sourceSheet = srcBook.getSheet("Testcases");
        int rowCount = sourceSheet.getLastRowNum();
        for (int i=1; i<=rowCount; i++){
            int rownum=i;
                XSSFRow testcaserow=sourceSheet.getRow(rownum);
                XSSFCell testcase_Name= testcaserow.getCell(1);
                String flagState=testcaserow.getCell(2).getStringCellValue();
            if (flagState.equals("yes")) {
            
            if (testcase_Name != null) {
                try {
                    Method myMethod = ATSmoke.class.getMethod(testcase_Name.getStringCellValue());
                    myMethod.invoke(new ATSmoke());
                } catch (NoSuchMethodException | SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("");
            } 
        }
        }
        try {
            srcBook.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

public class Profile extends ATTestDriver {

    public Profile(Browsers browser) {
        super(browser);
    }

    public void edit_contact_info() {
        WebElement pageopened =this.waitForElement(By.cssSelector(".qualifications p b b"));
        System.out.println("you have " +pageopened.getText());
        
        driver.findElement(By.cssSelector("contact-information button")).click();
        
        }
}

【问题讨论】:

  • profileDriver.edit_contact_info()?

标签: java excel selenium methods invoke


【解决方案1】:

你可以使用java反射来动态执行方法。

try {
    Class<?> c = Class.forName(args[0]);
    Object t = c.newInstance();

    Method[] allMethods = c.getDeclaredMethods();
    for (Method m : allMethods) {
    String mname = m.getName();
    if (!mname.startsWith("test")
        || (m.getGenericReturnType() != boolean.class)) {
        continue;
    }
    Type[] pType = m.getGenericParameterTypes();
    if ((pType.length != 1)
        || Locale.class.isAssignableFrom(pType[0].getClass())) {
        continue;
    }

    out.format("invoking %s()%n", mname);
    try {
        m.setAccessible(true);
        Object o = m.invoke(t, new Locale(args[1], args[2], args[3]));
        out.format("%s() returned %b%n", mname, (Boolean) o);

    // Handle any exceptions thrown by method to be invoked.
    } catch (InvocationTargetException x) {
        Throwable cause = x.getCause();
        err.format("invocation of %s failed: %s%n",
               mname, cause.getMessage());
    }
    }

    // production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
    x.printStackTrace();
} catch (InstantiationException x) {
    x.printStackTrace();
} catch (IllegalAccessException x) {
    x.printStackTrace();
}

来源:[https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html][1]

【讨论】:

    【解决方案2】:

    要调用另一个类中的方法,您首先必须实例化它:

    MyClass myClass = new MyClass();
    myclass.mymethod();
    

    或者在您的具体情况下:

     Profile profile = new Profile(browser);
     profile.edit_contact_info();
    

    【讨论】:

    • 这就是我所做的 Profile profileDriver = new Profile(Browsers.CHROME)
      当我指定 Method myMethod = Profile.class.getMethod(testcase_Name.getStringCellValue()); myMethod.invoke(new Profile()) 它不工作
    • @Vin 好的,所以您正在尝试通过反射动态调用方法,并且您知道仅在运行时调用哪个方法,对吗?你能发布错误/异常吗?
    • 如果我更改为以下内容并尝试我收到如下所列的错误消息,请尝试 { Method myMethod = Profile.class.getMethod(testcase_Name.getStringCellValue()); //方法 myMethod = ILMSSmoke.class.getMethod(testcase_Name.getStringCellValue()); //myMethod.invoke(ilms.Profile.class); myMethod.invoke(新配置文件(空)); java.lang.NullPointerException java.lang.NoSuchMethodException: ilms.profile.Profile.edit_contact_info()
    • 当我按照你所说的方法尝试时 Method myMethod = Profile.class.getMethod(testcase_Name.getStringCellValue()); myMethod.invoke(Profile.class);我得到了同样的错误 java.lang.NoSuchMethodException: ilms.profile.Profile.edit_contact_info()
    • 所以要清楚我在 excel 中的数据将是这样的 code_ s.no Testcase_name 执行 Class 1 pageopen 是 ATTestdriver 2 edit_contact_info 是 Profile 3 viewDayDetails 是 Schedule_ 当我读取数据时,我需要更改 myMethod 中关于 Testcase_name 的类名
    猜你喜欢
    • 2014-11-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多