Groovy是否具有C#中的扩展方法? [英] Does Groovy have extension methods like in C#?
本文介绍了Groovy是否具有C#中的扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以像在C#中那样将方法添加到最终类中吗?
Can I add to a method to a final class somehow like in C#?
所以我可以做类似的事情:
So I could do something like:
"Some text".myOwnFunction();
代替:
MyStaticClass.myOwnFunction("Some text");
推荐答案
您可以通过metaClass将其添加到所有将来的字符串实例中
You can either add it to all future string instances via the metaClass
String.metaClass.myOwnFunction = {-> delegate.length() }
assert "Tim".myOwnFunction() == 3
或者您可以将其添加到单个实例中
Or you can add it to a single instance
String a = "Tim"
a.metaClass.myOwnFunction = {-> delegate.length() }
assert a.myOwnFunction() == 3
Or you can add these methods when a jar is in the classpath at startup with extension modules
这篇关于Groovy是否具有C#中的扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文