Groovy 中@Delegate 和@Mixin AST 转换的区别 [英] Difference between @Delegate and @Mixin AST transformations in Groovy

查看:33
本文介绍了Groovy 中@Delegate 和@Mixin AST 转换的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Delegate@Mixin Groovy 中的 AST 转换.

What's the difference between @Delegate and @Mixin AST transformations in Groovy.

也许我的问题与 OO 以及何时应用不同的模式有关,但我同时使用两者并且可以实现相同的行为.

Maybe my question has to do with OO and when apply different patterns, but I use both and I can achieve the same behavior.

class Person {
    String name = "Clark"
    def walk() { "Walk" }
}

@Mixin(Person)
class Superhero {
    def fly() { "Fly" }
}

def superman = new Superhero()
assert superman.name == "Clark"
assert superman.walk() == "Walk"
assert superman.fly() == "Fly"

<小时>

class Person {
    String name = "Clark"
    def walk() { "Walk" }
}

class Superhero {
    @Delegate Person person
    def fly() { "Fly" }
}

def superman = new Superhero(person: new Person())
assert superman.name == "Clark"
assert superman.walk() == "Walk"
assert superman.fly() == "Fly"

推荐答案

行为类似,但@Delegate@Mixin 的实现完全不同.

The behavior is similar, but @Delegate and @Mixin are implemented completely differently.

@Delegate 在编译时生成访问器方法.Superhero 将有一个名为 walk() 的方法,它只调用 person.walk().生成的方法可以通过使用javap转储Superhero类文件来查看.

@Delegate generates accessor methods at compile time. Superhero will have a method called walk() that simply calls person.walk(). The generated methods can be seen by dumping the Superhero class file with javap.

@Mixin,另一方面只是创建一个小的存根,在运行时混合在 Person 方法中.它使用 groovy 的元对象协议来允许 Superhero 响应 Person 的方法.在这种情况下,您将不会在 Superhero.class 中看到任何 Person 方法.

@Mixin, on the other hand just creates a small stub that mixs in the Person methods at runtime. It uses groovy's meta-object protocol to allow Superhero to respond to Person's methods. In this case, you won't see any Person methods in Superhero.class.

@Delegate 的优点是方法可以从 Java 调用,并且避免了动态调用.另外,@Mixin 不能用属性来扩充类.

@Delegate has the advantage that the methods are callable from Java and it avoids doing a dynamic invocation. In addition, @Mixin can't augment the class with properties.

这篇关于Groovy 中@Delegate 和@Mixin AST 转换的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆