java 将字符串与变量名匹配并传递变量值

java match string to variable name and pass the variable's value

我是 Cucumber Selenium 的入门者 Java 并且已经 Google'd,但找不到是否可能。这就是问题所在。我有一个方法,它有一个 String 参数,我想将其匹配到一个变量名。然后我想将该变量用于另一种方法。

所以简而言之,我会有一个参数字符串 (f.e。"name") 并希望将其与变量 'name' 和 get/use 匹配,该值

类似这样。

我的黄瓜方案会有这样的步骤:

Abstract Scenario: check errors in fields
If there is an error in "field"
Then foo

Examples:
|field  |
|name   |
|address|
|phone  |

我在步骤定义中的方法类似于:

private final name = "field_ID_Name"
private final address = "field_ID_Address"
private final phone = "field_ID_Phone"

public void thereIsAnErrorIn(String field){
// Here the match from the argument "name" to use of the variable "name"
checkError(field)
}

private void checkError(String field){
// here I'd like to check based on the value, so in my case for variable
//'name' would get "field_ID_name" as passed parameter
seleniumdriver.pollVisible(field) //field = "field_ID_Name"
}

现在(很明显)它将 "name" 作为字符串传递,但对于此示例,我想不出一种传递 "field_ID_Name" 的方法。 我可以使用 switch 语句来检查字段的各种可能值,但我宁愿让它根据传递的字符串进行匹配。将确切定位器作为第一种方法的参数的另一种选择,但对于必须了解功能文件(黄瓜场景)的客户来说,这并不容易阅读。

感谢任何建议!

您可以使用 Java 反射 API 读取对象字段值,最简单的方法是使用 Apache BeanUtils 库。看看这个类似的回答问题:

Retrieve field values using BeanUtils

您可以创建一个映射,其中变量名作为键,所需参数作为值传递给 pollVisible 函数。 所以你的地图看起来像:

我的地图:名称 -> field_ID_Name

现在做:

private void checkError(字符串字段){

seleniumdriver.pollVisible(myMap.get(字段));

}