Grails - 全球可用的方法和元类编程 [英] Grails - Making Methods Globally Available and Metaclass Programming

查看:101
本文介绍了Grails - 全球可用的方法和元类编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将这行插入到我的BootStrap类的init()中。
$ b $ pre $ Integer.metaClass.minutes = {60000L * delegate }

然后我无法从Job类(Quartz插件)使用它。我是否将这行代码放在其他位置以使其成为全局修改?



我也想知道在Grails中的所有类中使用函数的最佳方法。
像全局函数一样。是否会扩展Object元类?或者有更好的方法吗?

解决方案


我把这行代码放在别的地方它是一个全球性的修改?


使用 DelegatingMetaClass


我也想知道让Grails中的所有类都可用的最佳方法。像全球功能一样。是否会扩展Object元类?或者有更好的方法吗?

如果您希望函数是所有类的实例方法,那么您必须将其添加到metaClass Object (见上文)。如果没有,只需将该函数作为类的静态方法添加即可,就像您在Java中全局访问函数一样。


I inserted this line into my init() of my BootStrap class

Integer.metaClass.minutes = { 60000L * delegate }

I was then not able to use it from a Job class (Quartz plugin). Do I put this line of code somewhere else to make it a global modification?

I was also wondering the best way to make a function available inside all classes in Grails. Like a global function. Would it be to extend the Object metaclass? or is there a better way?

解决方案

Do I put this line of code somewhere else to make it a global modification?

Use the DelegatingMetaClass

I was also wondering the best way to make a function available inside all classes in Grails. Like a global function. Would it be to extend the Object metaclass? or is there a better way?

If you want the function to be an instance method of all classes, then you must add it to the metaClass of Object (see above). If not, simply add the function as a static method of a class, i.e. the same way you make functions globally accessible in Java.

这篇关于Grails - 全球可用的方法和元类编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆