prabhap
prabhap

Reputation: 161

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?

Upvotes: 16

Views: 5735

Answers (3)

Maicon Mauricio
Maicon Mauricio

Reputation: 3001

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

Upvotes: 1

rlovtang
rlovtang

Reputation: 5060

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

Upvotes: 31

Michael Borgwardt
Michael Borgwardt

Reputation: 346240

You can do that using metaprogramming:

MyClass.metaClass.aliasMethod = MyClass.metaClass.originalMethod

Upvotes: 3

Related Questions