开发者

How to do method aliasing in groovy?

开发者 https://www.devze.com 2023-01-21 18:51 出处:网络
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 .& ?

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
0

精彩评论

暂无评论...
验证码 换一张
取 消