Available Static Close Values ​​in Groovy

I would like to keep some properties in static closure and later access them during a method call:

class Person {  
static someMap = { key1: "value1", key2: "value2" }  
}

So, how can I write a method in Person that retrieves this stored data?

+3
source share
3 answers

For a simple case, you better use a card.

If you really want to evaluate it as a closure (perhaps to create your own DSL), you will need to change your syntax a bit, as John points out. Here is one way to do this, using the Builder class to evaluate the “something” closure within what is passed to the builder.

groovy / :

class SomethingBuilder {
    Map valueMap = [:]

    SomethingBuilder(object) {
        def callable = object.something
        callable.delegate = this
        callable.resolveStrategy = Closure.DELEGATE_FIRST
        callable()
    }

    def propertyMissing(String name) {
        return valueMap[name]
    }

    def propertyMissing(String name, value) {
        valueMap[name] = value
    }

    def methodMissing(String name, args) {
        if (args.size() == 1) {
            valueMap[name] = args[0]
        } else {
            valueMap[name] = args
        }
    }
}

class Person {
    static something = {
        key1 "value1"              // calls methodMissing("key1", ["value1"])
        key2("value2")             // calls methodMissing("key2", ["value2"])
        key3 = "value3"            // calls propertyMissing("key3", "value3")
        key4 "foo", "bar", "baz"   // calls methodMissing("key4", ["foo","bar","baz"])
    }
}

def builder = new SomethingBuilder(new Person())

assert "value1" == builder."key1"  // calls propertyMissing("key1")
assert "value2" == builder."key2"  // calls propertyMissing("key2")
assert "value3" == builder."key3"  // calls propertyMissing("key3")
assert ["foo", "bar", "baz"] == builder."key4"  // calls propertyMissing("key4")
+7

, , - , .

. , - . , , , . .

static someClosure = { key1 = "value1"; key2 = "value2" } // set variables
static someClosure = { key1 "value1"; key2 = "value2" } // call methods
static someClosure = { [key1: "value1", key2: "value2"] } // return a map

, , , .

, .

static someMap = [key1: "value1", key2: "value2"]
+6

, , :

class ClosureProps {

       Map props = [:]  
       ClosureProps(Closure c) {  
           c.delegate = this  
           c.each{"$it"()}  
       }  
       def methodMissing(String name, args) {  
           props[name] = args.collect{it}  
       }  
       def propertyMissing(String name) {  
           name  
       }  
}  

// Example  
class Team {

        static schema = {  
            table team  
            id teamID  
            roster column:playerID, cascade:[update,delete]  
        }  
}  
def c = new ClosureProps(Team.schema)  
println c.props.table  
0

Source: https://habr.com/ru/post/1729795/


All Articles