我可以在Groovy中传递一个方法代替闭包吗?

时间:2014-09-27 23:03:42

标签: groovy

我们说我有这样的事情:

class Test {

    def test_method() {
        def http = new HTTPBuilder("http://rest.request.com")
        http.request(groovyx.net.http.Method.GET) { req ->
            uri.path = "/path/to/rest/request"
            response.success = {resp, reader ->
                println resp
            }
        }
    }

}

这很好用,但我真的更喜欢这样做:

class Test {

    def print_resp(String resp) {
        println resp
    }

    def test_method() {
        def http = new HTTPBuilder("http://rest.request.com")
        http.request(groovyx.net.http.Method.GET) { req ->
            uri.path = "/path/to/rest/request"
            response.success = print_resp
        }
    }

}

除非我在那里弄错了语法。请帮助我理解我做错了什么。

1 个答案:

答案 0 :(得分:4)

你想使用。&语法:

def test_method() {
    def http = new HTTPBuilder("http://rest.request.com")
    http.request(groovyx.net.http.Method.GET) { req ->
        uri.path = "/path/to/rest/request"
        response.success = this.&print_resp
    }
}