开发者

Groovy :: @Mixin methods override target class methods

开发者 https://www.devze.com 2023-02-12 14:52 出处:网络
class A { def test() { println \"parent\" } } @Mixin(A) class B { def test() { println \"child\" } } new B().test() // prints \"parent\", but I am expecting it to print \"child\"
class A {  
  def test() { println "parent" }  
} 

@Mixin(A)  
class B {  
  def test() { println "child" }  
} 

new B().test() // prints "parent", but I am expecting it to print "child"

This looks like some kind of reverse inheritance.

Are mixins only to be used as a means to define new methods?

I can of course use conventional inheritance and go with extends, but the use case entails a form builder where each domain has a unique form implementation and I'd like to, in my application controller, catch form requests and do a MyUnique开发者_运维技巧DomainForm.mixin DefaultFormMethods (so I only need to define default methods when I need to, as well as not having to import my.package.app.DefaultFormMethods in each form class)


Whatever you mixin will overload whatever is already there...

In this example, at compile time B.test() overloads the inherited A.test() method

But then at runtime, A.test() is added via the mixin, which re-overloads the previously overloaded method

If it was not this way round you would not be able to alter the existing characteristics of a class using mixins

ie (this is a silly example, but I believe it gets my point across):

class AddNotMinus {
  static def minus( int a, int b ) {
     a + b
  }
}

Integer.mixin AddNotMinus
println 10 - 10

prints 20

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号