2014-09-23 52 views

回答

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

真的很全面的回答!太好了! – Opal 2014-09-23 18:35:20

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']