2

是否可以从字符串动态地将属性添加到 Groovy 类?
例如,我要求用户插入字符串,比如“HelloString”
,然后将属性 HelloString 添加到现有的 Groovy 玻璃中?

4

2 回答 2

5

有几种方法可以解决这个问题。例如,您可以使用propertyMissing

class Foo {
   def storage = [:]
   def propertyMissing(String name, value) { storage[name] = value }
   def propertyMissing(String name) { storage[name] }
}
def f = new Foo()
f.foo = "bar"

assertEquals "bar", f.foo

对于现有的类(任何类),您可以使用ExpandoMetaClass

class Book {
  String title
}
Book.metaClass.getAuthor << {-> "Stephen King" }

def b = new Book("The Stand")

assert "Stephen King" == b.author

或仅使用Expando该类:

def d = new Expando()
d."This is some very odd variable, but it works!" = 23
println d."This is some very odd variable, but it works!"

@Delegate以地图作为存储:

class C {
    @Delegate Map<String,Object> expandoStyle = [:]
}
def c = new C()
c."This also" = 42
println c."This also"

这就是您通过 var 设置属性的方式:

def userInput = 'This is what the user said'
c."$userInput" = 666
println c."$userInput"
于 2014-09-23T10:38:20.393 回答
1

如果属性名称和属性值都是动态的,您可以执行以下操作:

// these are hardcoded here but could be retrieved dynamically of course...
def dynamicPropertyName = 'someProperty'
def dynamicPropertyValue = 42

// adding the property to java.lang.String, but could be any class...
String.metaClass."${dynamicPropertyName}" =  dynamicPropertyValue


// now all instances of String have a property named "someProperty"
println 'jeff'.someProperty
println 'jeff'['someProperty']
于 2014-09-24T07:06:44.133 回答