是否可以从字符串动态地向Groovy类添加属性?
例如,我要求用户插入字符串,说'HelloString'
我将属性HelloString添加到现有的Groovy玻璃?
答案 0 :(得分:4)
有几种方法可以解决这个问题。例如。你可以使用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"
答案 1 :(得分: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']