以下代码试图替换 Groovy 类中的现有方法:
The following code tried to replace an existing method in a Groovy class:
class A { void abc() { println "original" } } x= new A() x.abc() A.metaClass.abc={-> println "new" } x.abc() A.metaClass.methods.findAll{it.name=="abc"}.each { println "Method $it"} new A().abc()结果如下:
original original Method org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod@103074e[name: abc params: [] returns: class java.lang.Object owner: class A] Method public void A.abc() new这是否意味着在修改元类时,将其设置为闭包,它并没有真正替换它,而只是添加了另一个可以调用的方法,从而导致元类具有两个方法?是否有可能真正替换该方法,以便第二行输出打印new"?
Does this mean that when modify the metaclass by setting it to closure, it doesn't really replace it but just adds another method it can call, thus resulting in metaclass having two methods? Is it possible to truly replace the method so the second line of output prints "new"?
在试图弄清楚时,我发现 DelegatingMetaClass 可能帮助 - 这是最Groovy 的方式吗?
When trying to figure it out, I found that DelegatingMetaClass might help - is that the most Groovy way to do this?
推荐答案您可以使用每个实例的元类来更改现有对象中的值,如下所示:
You can use the per-instance metaClass to change the value in the existing object like so:
x= new A() x.abc() x.metaClass.abc={-> println "new" } x.abc() x.metaClass.methods.findAll{it.name=="abc"}.each { println "Method $it"}但是正如你所看到的,x 将有两个方法与之关联(嗯,实际上,一个方法和你添加的闭包
But as you have seen, x will have two methods associated with it (well, in actual fact, a method and the closure you added
如果你改变 A 的定义,使该方法变成一个闭包定义,如下所示:
If you change the definition of A so that the method becomes a closure definition like so:
class A { def abc = { -> println "original" } }那么你在metaClass中只会得到一个闭包,修改后没有方法
Then you will only get a single closure in the metaClass and no method after the alteration
更多推荐
是否可以替换现有对象的常规方法?
发布评论