是否可以替换现有对象的常规方法?

编程入门 行业动态 更新时间:2024-10-22 23:03:31
本文介绍了是否可以替换现有对象的常规方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下代码试图替换 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

更多推荐

是否可以替换现有对象的常规方法?

本文发布于:2023-10-31 04:15:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常规   对象   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!