Groovy Mixin on Instance (Dynamic Mixin)

后端 未结 1 1845
我寻月下人不归
我寻月下人不归 2021-01-05 15:02

I\'m trying to achieve following:

class A {
  def foo() { \"foo\" }
}

class B {
  def bar() { \"bar\" }
}

A.mixin B
def a = new A()

a.foo() + a.bar()


        
相关标签:
1条回答
  • 2021-01-05 15:46

    You can do this since Groovy 1.6

    Call mixin on the instance metaClass like so:

    class A {
      def foo() { "foo" }
    }
    
    class B {
      def bar() { "bar" }
    }
    
    def a = new A()
    a.metaClass.mixin B
    
    a.foo() + a.bar()
    
    0 讨论(0)
提交回复
热议问题