开发者

Expand Abstract Java Class for all instances

I'm working on a grails application atm. I need a property on an abstract java class (org.quartz.Trigger) adding

Trigger.metaClass.id = { delegate.hashCode() 开发者_开发百科}

before I call the class works. I would like to enable this for all my Triggers in my application. Is this possible? Or do I have to repeat this everytime I need the property?


If you add to the metaClass before any Trigger objects are instantiated, then this addition will exist in all of them.

However, after they are created, you would need to add it to every instance of Trigger.

Of course, this method will only be visible from Groovy, as Java does not know about the metaClass.

Some example Groovy code showing this in action:

// Add to the metaClass of an anstract java class
AbstractList.metaClass.woo = { 'hi there' }

// Create an instance of a class that extends this abstract class
ArrayList list = [ 1, 2, 3 ]

// Call the closure in the metaClass
println list.woo()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜