2014-09-23 2 views

답변

4

이 문제를 해결할 수있는 방법은 여러 가지가 있습니다. 예 :

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!" 
,369 : 당신은 당신이 단지 Expando 클래스를 사용하여 ExpandoMetaClass

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

def b = new Book("The Stand") 

assert "Stephen King" == b.author 

또는를 사용하여 기존 클래스에 대한 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 

(모든 클래스)를 사용할 수 있습니다

또는 저장 등의지도에 @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

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'] 
관련 문제