如何动态组合变量名?

时间:2014-08-11 07:42:26

标签: groovy

我需要生成一个列表,并根据for循环索引命名它的项目 数字,像这样:

for(int i=0;i<someNumber;i++){
    Model m_{$i}=Mock()   //but this doesn't work
    ......
    models.add(i,m_{$i})
}

然后在eclipse中调试测试代码(羞于告诉这个)时可以通过名称区分它们,但是它不起作用,那么如何使它工作?

更新:添加图片以告诉我为什么要将for循环索引附加到变量名称 enter image description here

1 个答案:

答案 0 :(得分:1)

由于Groovy的MetaClass,您还可以在运行时向Mock类添加一些属性。请看一下此示例代码段:

class myClass {
    String someProperty
}

def models = []
10.times { it ->
    def instance = new myClass(someProperty: "something")
    instance.metaClass.testId = it
    models.add(instance)
}

// delete some
println "Removing object with testId = " + models.remove(4).testId
println "Removing object with testId = " + models.remove(7).testId

def identifiersOfObjectsAfterRemoves = models.collect { it.testId }

def removedObjectsIdentifiers = (0..9) - identifiersOfObjectsAfterRemoves

println "Identifiers of removed objects: " + removedObjectsIdentifiers