Groovy 是否有像 C# 中那样的扩展方法?

Does Groovy have extension methods like in C#?

我可以像在 C# 中一样将方法添加到最终 class 吗?

所以我可以这样做:

"Some text".myOwnFunction();

而不是:

MyStaticClass.myOwnFunction("Some text");

您可以通过元类将其添加到所有未来的字符串实例中

    String.metaClass.myOwnFunction = {-> delegate.length() }
    assert "Tim".myOwnFunction() == 3

或者您可以将其添加到单个实例

    String a = "Tim"
    a.metaClass.myOwnFunction = {-> delegate.length() }
    assert a.myOwnFunction() == 3

或者您可以在启动时类路径中有 jar 时使用 extension modules

添加这些方法