Suppose I have this code:
MyClass obj1 = new MyClass()
MyClass obj2 = new MyClass()
The toString() method in MyClass.groovy is implemented like this:
String toString() {
"Instance of MyClass"
}
However, I would like obj1 to return something else when printed. How would I do that? I tried these two options, but neither worked.
obj1.metaClass.toString = {
"Object 1"
}
and
obj1.toString = {
"Object 1"
}
The first simply didn't work and the second caused an error. What is the correct way to do this in Groovy?