Does Groovy have extension methods like in C#?

谁说我不能喝 提交于 2019-11-30 22:49:33

问题


Can I add to a method to a final class somehow like in C#?

So I could do something like:

"Some text".myOwnFunction();

Instead of:

MyStaticClass.myOwnFunction("Some text");

回答1:


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



来源:https://stackoverflow.com/questions/36954719/does-groovy-have-extension-methods-like-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!