Java、Selenium和Method.invoke():获取NoSuchMethodException

Java、Selenium和Method.invoke():获取NoSuchMethodException,java,selenium,selenium-webdriver,nosuchmethoderror,Java,Selenium,Selenium Webdriver,Nosuchmethoderror,目标:创建我自己的方法,调用传入其中的Selenium方法,并重复该方法指定的次数 问题:无论我尝试什么,以下代码总是导致: java.lang.NoSuchMethodException:org.openqa.selenium.WebDriver.sendKeys() 讨论:据我所知,sendKeys()是org.openqa.selenium.WebDriver中/的一种方法 问题代码: 方法objTest=WebDriver.class.getMethod(strMethod,CharSe

目标:创建我自己的方法,调用传入其中的Selenium方法,并重复该方法指定的次数

问题:无论我尝试什么,以下代码总是导致: java.lang.NoSuchMethodException:org.openqa.selenium.WebDriver.sendKeys()

讨论:据我所知,sendKeys()是org.openqa.selenium.WebDriver中/的一种方法

问题代码:

方法objTest=WebDriver.class.getMethod(strMethod,CharSequence.class)

其中strMethod=sendKeys

代码

public void repeatAction(String strMethod, int numberOfTimes) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    int i = 0;
    Method objTest = WebDriver.class.getMethod(strMethod, CharSequence.class); // PROBLEM CODE - results in NoSuchMethodException
    while (i <= numberOfTimes) {
        objTest.invoke(strMethod, Keys.DOWN);  // I've hardcoded Keys.DOWN for now but will make this flexible later
        i++;
    }
}
运行时错误

Exception in thread "main" java.lang.NoSuchMethodException: org.openqa.selenium.WebDriver.sendKeys(java.lang.CharSequence)
at java.base/java.lang.Class.getMethod(Class.java:2109)
at AutocompleteDropdownPractice.repeatKeysAction(AutocompleteDropdownPractice.java:17)
at AutocompleteDropdownPractice.main(AutocompleteDropdownPractice.java:45)
对于我所做的错误以及我应该如何做的任何帮助,我们将不胜感激。

如果您查看,您将看到没有任何
WebDriver
类作为sendKeys()的方法,这正是您获得NoSuchMethodException的原因

我想您正在寻找
org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence…keystend)
方法,在您的例子中,您可以按如下方式使用它:

Method objTest = WebElement.class.getMethod(strMethod, CharSequence[].class);
我使用数组版本
CharSequence[].class
而不是
CharSequence.class
,因为
sendKeys
方法接受一个
CharSequence.class
数组,该数组可以在中清楚地看到。

首先

如果参考Java文档,您将看到它包含两个参数:

  • 从中调用方法的对象(因为需要该对象来调用非静态方法)
  • 方法参数
  • 示例中的这些行:

    methodobjtest=WebDriver.class.getMethod(strMethod,CharSequence.class);
    调用对象测试(strMethod,Keys.DOWN);
    
    这意味着您从
    WebDriver
    类中获取方法,并在
    String
    对象上调用它,这是不正确的

    sendKeys
    方法在
    WebElement
    界面中声明,而不是在
    WebDriver
    中声明

    第三

    您可以使用
    Proxy
    对象来完成您正在尝试的操作,如下所示:

    publicwebelement-poxiedElement(stringmethodname,int-times,WebElement){
    return(WebElement)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{WebElement.Class},new InvocationHandler()){
    @凌驾
    公共对象调用(对象o、方法、对象[]对象)抛出可丢弃的{
    对象[]结果=新对象[次数];
    if(methodName.equals(method.getName())){
    for(int i=0;i
    p.S.-您应该了解方法可以返回值。因此多次调用任何方法可能会返回多个值。你必须考虑这一点。在我的示例中,该方法将返回结果的
    array

    Method objTest = WebElement.class.getMethod(strMethod, CharSequence[].class);