Does Groovy have extension methods like in C#?

前端 未结 1 1561
傲寒
傲寒 2021-01-04 03:46

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:

1条回答
  •  [愿得一人]
    2021-01-04 04:03

    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

    0 讨论(0)
提交回复
热议问题