2014-09-23 2 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" 

И это, как вы установите свойство с помощью вар:

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'] 
Смежные вопросы