关于闭包和groovy builder模式

关于闭包和groovy builder模式,groovy,Groovy,开始掌握闭包和groovy的一些特性 给定以下代码: class Mailer { void to(final String to) { println "to $to" } void from(final String from) { println "from $from" } static void send(Closure configuration) { Mailer mailer = new Mailer() mailer.w

开始掌握闭包和groovy的一些特性

给定以下代码:

class Mailer {
    void to(final String to) { println "to $to" }
    void from(final String from) { println "from $from" }

    static void send(Closure configuration) {
        Mailer mailer = new Mailer()
        mailer.with configuration
    }  
}

class MailSender {
    static void sendMessage() {
        Mailer.send {
            to 'them'
            from 'me'
        }
    }
}

MailSender.sendMessage()
当你向
Mailer.send
方法传递闭包时,引擎盖下会发生什么

从闭包的角度来看,
to
from
是否作为参数传递?哪些类型的闭包映射它们

然后在Mailer对象调用
Mailer时,在
Mailer.send
方法中发送。当
接收
配置
对象时,对象将它们映射到方法调用中。Groovy通过反射来实现这一点?

Groovy可以动态地定义闭包,甚至
this
对象

with
正在设置委托并执行闭包。这是实现相同目标的详细方法:

def math = {
    given 4
    sum 5
    print
}


class PrintMath {
    def initial
    def given(val) {
        initial = val
    }

    def sum(val) {
        initial += val
    }

    def getPrint() {
        println initial
        return initial
    }
}

math.delegate = new PrintMath()
math.resolveStrategy = Closure.DELEGATE_ONLY

assert math() == 9

当您将闭包传递给Mailer.send方法时,引擎盖下会发生什么

它接收一个尚未执行的代码块

从闭包的角度来看,to和from是否作为参数传递

不,最好将它们看作java中的匿名类/lambda,或者javascript中的
function(){}

哪些类型的闭包映射它们

无,它们是等待执行的方法调用。不过,它们可以委托给不同的对象

然后在Mailer对象调用Mailer.send方法时,在Mailer.send方法中。接收到配置对象后,对象将它们映射到方法调用中。Groovy是通过反射实现的吗

你可以看看发生了什么。IIRC,Groovy目前使用一种“反射器”策略(带有
arrayOfCallSite
缓存)来更快地调用,或者它可以使用
invokedynamic

上述代码中的闭包
math
将导致该类:

// .. a lot of techno-babble

public Object doCall(Object it) {
    CallSite[] arrayOfCallSite = $getCallSiteArray();
    arrayOfCallSite[0].callCurrent(this, Integer.valueOf(4));
    arrayOfCallSite[1].callCurrent(this, Integer.valueOf(5));
    return arrayOfCallSite[2].callGroovyObjectGetProperty(this);
    return null;
}