【问题标题】:Groovy MetaClass - Add category methods to appropriate metaClassesGroovy MetaClass - 将类别方法添加到适当的元类
【发布时间】:2011-01-24 03:38:41
【问题描述】:

我在 Grails 插件中使用了几个类别。例如,

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

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

aInstance.foo(someArg)

bInstance.bar(someArgs)

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

【问题讨论】:

    标签: grails groovy categories metaclass mixins


    【解决方案1】:

    在 Groovy 1.6 中,引入了一种更简单的使用类别/mixin 的机制。以前类别类的方法必须声明为静态,第一个参数指示它们可以应用于哪个对象类(如上面的Foo 类)。

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

    无论如何,从 Groovy 1.6 开始,您可以改为这样做

    // 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 是您可以这样做的地方。

    【讨论】:

      猜你喜欢
      • 2013-11-15
      • 1970-01-01
      • 2010-12-09
      • 2017-01-02
      • 1970-01-01
      • 2012-02-10
      • 2013-01-13
      • 2010-12-28
      • 1970-01-01
      相关资源
      最近更新 更多