Groovy MetaClass - 将类别方法添加到适当的元类
我在 Grails 插件中使用了几个类别。例如,
class Foo {
static foo(ClassA a,Object someArg) { ... }
static bar(ClassB b,Object... someArgs) { ... }
}
我正在寻找将这些方法添加到元类的最佳方法,以便我不必使用类别类,而只需将它们作为实例方法调用。例如,
aInstance.foo(someArg)
bInstance.bar(someArgs)
是否有 Groovy/Grails 类或方法可以帮助我做到这一点,或者我是否只能迭代这些方法并自己添加它们?
I have several categories that I use in my Grails plugin. e.g.,
class Foo {
static foo(ClassA a,Object someArg) { ... }
static bar(ClassB b,Object... someArgs) { ... }
}
I'm looking for the best way to add these methods to the meta-classes so that I don't have to use the category classes and can just invoke them as instance methods. e.g.,
aInstance.foo(someArg)
bInstance.bar(someArgs)
Is there a Groovy/Grails class or method that will help me do this or am I stuck iterating through the methods and adding them all myself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Groovy 1.6 中引入了一种更简单的使用类别/混合的机制。以前,类别类的方法必须声明为静态,第一个参数指示它们可以应用于哪个类的对象(如上面的
Foo
类中所示)。我觉得这有点尴尬,因为一旦类别的方法“混合”到目标类中,它们就是非静态的,但在类别类中它们是静态的。
无论如何,从 Groovy 1.6 开始,您可以这样做。还有
一些其他功能可用。如果要限制类别可以应用的类,请使用@Category注释。例如,如果您只想将
MyCategory
应用于MyClass
(或其子类),请将其定义为:而不是在编译时使用
混合类别@Mixin
(如上所述),您可以在运行时混合它们,而不是使用:在您使用 Grails 时,您可以在
Bootstrap.groovy
中执行此操作。In Groovy 1.6 a much simpler mechanism for using categories/mixins was introduced. Previously the methods of a category class had to be declared static, and the first parameter indicates which class of objects they could be applied to (as in your
Foo
class above).I find this somewhat awkward because once the methods of the category are "mixed in" to the target class they are non-static, but in the category class they are static.
Anyway, since Groovy 1.6 you can do this instead
A few other features are available. If you want to restrict the classes that the category can be applied to, use the
@Category
annotation. For example, if you only want to applyMyCategory
toMyClass
(or it's subclasses), define it as:Instead of mixing the categories in at compile-time using
@Mixin
(as above), you can mix them in at runtime instead using:In you're using Grails,
Bootstrap.groovy
is a place where you might do this.