从字段

时间:2017-01-26 21:23:37

标签: java selenium appium

假设我有以下基于Page Factory的代码

@AndroidFindBy(id = "cancel_action")
@CustomLog("Cancel Button")
public MobileElement btnCancel;

@AndroidFindBy(id = "ok_action")
@CustomLog("ok Button")
public MobileElement btnOk;


public void tap(MobileElement element) {
    element.tap(1, 500);
    //add the reflection code to print the value of CustomLog annotation
}

现在,如果我按下面的方式调用tap方法,它应该打印{Custom {1}}

的“CustomLog”注释的值
btnCancel

我可以成功tap(btnCancel); 指定tap MobileElement,因为它知道必须使用注释element点击id = "cancel_action" 现在,如果我想访问我的测试中的“取消按钮”的自定义注释(@AndroidFindBy)值,是否可以?我创建了一个名为“CustomLog”的注释但是如何在@CustomLog

的一部分中访问此注释的值

1 个答案:

答案 0 :(得分:1)

如果您想在运行时获取自定义注释(“取消按钮”)的值,则可以采用反射方式。

首先,确保您的注释具有rention RUNTIME,否则在编译代码后它将不再存在:

@Retention(RetentionPolicy.RUNTIME)
public static @interface MyAnnotation {
  String value();
}

然后你就可以使用你已经拥有的注释:

@MyAnnotation("test")
public MobileElement element;

只需检索特定字段Field的注释:

Field field = this.getClass().getDeclaredField("element");

从注释中获取value()

MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
System.out.println(annotation.value());

所以在我的例子中,那会将“test”打印到控制台。

相关问题