簡體   English   中英

在Groovy中訪問靜態閉包的值

[英]Access values of static closure in Groovy

我想在靜態閉包中存儲一些屬性,然后在方法調用期間訪問它們:

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

那么如何在Person中編寫一個方法來檢索這些存儲的數據呢?

對於簡單的情況,您最好使用地圖。

如果你真的想把它評估為一個閉包(可能是為了創建你自己的DSL),你需要稍微改變你的語法,就像John指出的那樣。 這是使用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")

如果需要通過閉包而不是映射來初始化它們,那么有人必須運行閉包以便在設置時拾取並記錄值。

你的語法無效。 記住閉包只是匿名方法。 您的語法看起來像是在嘗試定義映射,但是閉包需要調用方法,設置變量或返回映射。 例如

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

這就是我提出的提取靜態閉包屬性的方法:

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  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM