Take the 2-minute tour ×

What is correct way to change method signature for single java object. Suppose I wanna change toString method.

myObject.metaClass.toString = { pritln "hello world" }

Looks like this code has problems. If I pass my object into other Java compiled object original toString will be called.

Other solution creates wrapper Object. It has different class from original one so it doesn't satisfy me

1. I can't control creation process
2. I don't know how object was instantiated

So there is no groovy way to solve this problem? The only solution is to create Java wrapper class, wrap all methods and change one? This is a ...

share|improve this question

4 Answers 4

up vote 2 down vote accepted

any changes you make to the metaClass are only visible to groovy.

java has no idea the metaClass exists, so obviously cannot call any replacement methods defined by it

share|improve this answer

If you would like to create an object that has a single method changed, there is a way to do that using "Anonymous Classes".

Whenever creating your object:

MyClass myObject = new MyClass() {
    public String toString() {
share|improve this answer

Can you use an annoymous subclass? That will only override the toString() method in that single instance.

MyObject myObject= new MyObject (){
    public String toString (){
         println "hello world"
share|improve this answer

Create a Wrapper that extends the Original:

public class wrapper extends myObject{
    public toString{
        System.out.println("hello world");
share|improve this answer
OP stated he didn't want to use a wrapper class. –  JavaKungFu Nov 13 '12 at 22:24

Your Answer


