Groovy中@Delegate和@Mixin AST转换之间的区别 [英] Difference between @Delegate and @Mixin AST transformations in Groovy
问题描述
@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
在编译时生成访问器方法。超级英雄将有一个名为 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.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屋!