How to do method aliasing in groovy?
I am trying to redefine dynamic methods of a domain in groovy. Is there something开发者_运维技巧 similar alias method in ruby in groovy?
Do you mean like the method reference operator .&
?
def out = System.out.&println
out << "Hello"
and
def greet(name) {
println "Hello $name"
}
def sayHello = this.&greet
sayHello "Ronny"
It is mentioned at http://groovy.codehaus.org/Operators but an example is missing
You can do that using metaprogramming:
MyClass.metaClass.aliasMethod = MyClass.metaClass.originalMethod
Apart from the method pointer operator (.&
), there's the equivalent method reference operator (::
) for Groovy version 3.0.0 and above which is more compatible with Java. Read my answer on this other thread.
def foo(bar) {
println "foo $bar"
}
def bar = this.&foo
bar "foo"
def out = System.out::println
out << "Hello"
Output
foo foo
Hello
精彩评论