假设我有以下基于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 方法,它应该打印 btnCancel
的“CustomLog”注释的值
tap(btnCancel);
我将能够成功点击
指定的MobileElement
元素
,因为它知道必须点击id = "cancel_action”
使用注释 @AndroidFindBy
现在,如果我想访问自定义注释(@CustomLog
)值,即我的测试中的“取消按钮”,是否可以?我创建了一个名为“CustomLog”的注释,但是如何访问此注释的值作为此 MobileElement
最佳答案
如果您想在运行时获取自定义注释(“取消按钮”)的值,反射是最佳选择。
首先,请确保您的注释具有租赁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”打印到控制台。
关于java - 从字段上的自定义注释访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41883224/