【发布时间】:2019-08-24 01:41:33
【问题描述】:
我想知道是否可以检索变量的名称。
例如,如果我有一个方法:
def printSomething(def something){
//instead of having the literal String something, I want to be able to use the name of the variable that was passed
println('something is: ' + something)
}
如果我这样调用这个方法:
def ordinary = 58
printSomething(ordinary)
我想得到:
ordinary is 58
另一方面,如果我这样调用这个方法:
def extraOrdinary = 67
printSomething(extraOrdinary)
我想得到:
extraOrdinary is 67
编辑
我需要变量名,因为我有这个在 Katalon Studio 中的每个 TestSuite 之前运行的代码 sn-p,基本上它为您提供了使用传递 GlobalVariables 的灵活性一个katalon.features 文件。思路来自:kazurayam/KatalonPropertiesDemo
@BeforeTestSuite
def sampleBeforeTestSuite(TestSuiteContext testSuiteContext) {
KatalonProperties props = new KatalonProperties()
// get appropriate value for GlobalVariable.hostname loaded from katalon.properties files
WebUI.comment(">>> GlobalVariable.G_Url default value: \'${GlobalVariable.G_Url}\'");
//gets the internal value of GlobalVariable.G_Url, if it's empty then use the one from katalon.features file
String preferedHostname = props.getProperty('GlobalVariable.G_Url')
if (preferedHostname != null) {
GlobalVariable.G_Url = preferedHostname;
WebUI.comment(">>> GlobalVariable.G_Url new value: \'${preferedHostname}\'");
} else {
WebUI.comment(">>> GlobalVariable.G_Url stays unchanged");
}
//doing the same for other variables is a lot of duplicate code
}
现在这只处理 1 个变量值,如果我为 20 个变量执行此操作,那就是很多重复的代码,所以我想创建一个辅助函数:
def setProperty(KatalonProperties props, GlobalVariable var){
WebUI.comment(">>> " + var.getName()" + default value: \'${var}\'");
//gets the internal value of var, if it's null then use the one from katalon.features file
GlobalVariable preferedVar = props.getProperty(var.getName())
if (preferedVar != null) {
var = preferedVar;
WebUI.comment(">>> " + var.getName() + " new value: \'${preferedVar}\'");
} else {
WebUI.comment(">>> " + var.getName() + " stays unchanged");
}
}
这里我只是放了 var.getName() 来解释我在寻找什么,这只是我假设的一种方法。
【问题讨论】:
-
@Carcigenicate 这不是纯粹出于好奇,我需要使用变量名将其传递给函数:
KatalonProperties.getProperty(String key),它根据属性名称检索属性的值。我可以将参数更改为字符串而不是 def 来控制传递给我的函数的内容...但我仍然需要知道如何获取变量的名称 -
不,不可能
-
@tim_yates 好吧,那真是太糟糕了:(
-
@AdityaT 不要认为它是重复的。那是关于获取参数名称。这是关于获取传递给方法的变量的名称
-
@tim_yate 用宏方法不可能,还是我错了?
标签: groovy metaprogramming katalon-studio