2016-04-30 8 views
2

C#のように最終的なクラスにメソッドに追加できますか?あなたはメタクラスGroovyにはC#のような拡張メソッドがありますか?

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

それとも経由して、将来のすべての文字列のインスタンスに追加することができますいずれか

MyStaticClass.myOwnFunction("Some text"); 

答えて

6

"Some text".myOwnFunction(); 

の代わりに:

だから私のような何かを行うことができます単一インスタンスに追加できます

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

また、起動時にクラスパスにjarがある場合は、これらのメソッドを追加できます。extension modules

関連する問題