代码之家  ›  专栏  ›  技术社区  ›  noah

Groovy元类-向适当的元类添加category方法

  •  1
  • noah  · 技术社区  · 16 年前

    class Foo {
        static foo(ClassA a,Object someArg) { ... }
        static bar(ClassB b,Object... someArgs) { ... }
    }
    

    我正在寻找将这些方法添加到元类的最佳方法,这样我就不必使用category类,只需将它们作为实例方法调用即可。例如。,

    aInstance.foo(someArg)
    
    bInstance.bar(someArgs)
    

    是否有一个Groovy/Grails类或方法可以帮助我实现这一点,还是我一直在迭代这些方法并自己添加它们?

    1 回复  |  直到 15 年前
        1
  •  4
  •   noah    16 年前

    Foo 以上级别)。

    我觉得这有点尴尬,因为一旦category的方法被“混合”到目标类中,它们就不是静态的,但是在category类中它们是静态的。

    // Define the category
    class MyCategory {
      void doIt() {
        println "done"
      }
    
      void doIt2() {
        println "done2"
      }
    }
    
    // Mix the category into the target class
    @Mixin (MyCategory)
    class MyClass {
       void callMixin() {
         doIt()
       }
    }
    
    // Test that it works
    def obj = new MyClass()
    obj.callMixin()
    

    @Category 注释。例如,如果你只想申请 MyCategory MyClass (或其子类),定义为:

    @Category(MyClass)
    class MyCategory {
      // Implementation omitted
    }
    

    @Mixin (如上所述),您可以在运行时将它们混合在一起,而不是使用:

    MyClass.mixin MyCategory
    

    在你使用Grails时, Bootstrap.groovy

    推荐文章