2
是否可以從字符串動態添加屬性到Groovy類?
例如,我要求用戶插入字符串,說'HelloString'
我添加屬性HelloString到現有的Groovy玻璃?將字符串添加到Groovy類
是否可以從字符串動態添加屬性到Groovy類?
例如,我要求用戶插入字符串,說'HelloString'
我添加屬性HelloString到現有的Groovy玻璃?將字符串添加到Groovy類
有幾種方法可以解決這個問題。例如。您可以使用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"
如果屬性名稱和屬性值各爲動態的,你可以這樣做:
// 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']
真的很全面的回答!太好了! – Opal 2014-09-23 18:35:20