先查看一下AjaxElementLocatorFactory的源生代码
package org.openqa.selenium.support.pagefactory;
import org.openqa.selenium.SearchContext;
import java.lang.reflect.Field;
public class AjaxElementLocatorFactory implements ElementLocatorFactory {
private final SearchContext searchContext;
private final int timeOutInSeconds;
public AjaxElementLocatorFactory(SearchContext searchContext, int timeOutInSeconds) {
this.searchContext = searchContext;
this.timeOutInSeconds = timeOutInSeconds;
}
public ElementLocator createLocator(Field field) {
return new AjaxElementLocator(searchContext, field, timeOutInSeconds);
}
}
AjaxElementLocatorFactory类是为了网页动态代码而存在的。最终目的是拿到一个ElementLocator类的对象。
首先需要定义一个AjaxElementLocatorFactory的类
Class<?> cls = Class.forName("com.testReflect.FieldDemo");
//使用FieldDemo类的class对象生成 实例
Object obj = cls.newInstance();
//通过Class类中getField(String name): 获取类特定的方法,name参数指定了属性的名称
Field field = cls.getField("num1");
AjaxElementLocatorFactory ajaxElementLocatorFactory = new AjaxElementLocatorFactory(driver, 5000);
ElementLocator elementLocator = ajaxElementLocatorFactory.createLocator(field);