fedor.belov
fedor.belov

Reputation: 23323

How can I change Java method implementation of single instance?

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


Added:
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 ...

Upvotes: 2

Views: 1935

Answers (4)

Brian
Brian

Reputation: 412

Create a Wrapper that extends the Original:

public class wrapper extends myObject{
    public toString{
        System.out.println("hello world");
    }
}

Upvotes: 1

TbWill4321
TbWill4321

Reputation: 8666

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() {
        ...implementation...
    }
}

Upvotes: 4

JavaKungFu
JavaKungFu

Reputation: 1314

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

MyObject myObject= new MyObject (){
    @Override
    public String toString (){
         println "hello world"
    }
};

Upvotes: 3

tim_yates
tim_yates

Reputation: 171054

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

Upvotes: 2

Related Questions