Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 241
fedor.belov Avatar asked Nov 17 '25 14:11

fedor.belov


1 Answers

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...
    }
}
like image 139
TbWill4321 Avatar answered Nov 19 '25 05:11

TbWill4321



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!