Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Java object instance with another and all references

Tags:

java

object

is there a way to replace an object in java with another one that updates all references to the first one to instead point to the second one? In C# this question was answered here: Replace object instance with another in C# but I was wondering if I could do this in Java. Thanks!

EDIT: 1. I want to replace the first object with a an object of a subtype. 2. I can't edit the implementation of the first object, that's why I'm replacing it with a subtype. I can edit the subtype.

like image 224
Leo Izen Avatar asked Jan 15 '23 17:01

Leo Izen


2 Answers

Don't don't this, even if you can. Instead, use another class to contain or wrap the object you want to replace. The container has to implement all the methods you need from the original by calling the methods in the original, but you can replace the wrapped class easily at any time. The wrapper, the original class, and the one you replace it with should all implement the same interface. This solution's a bit of work, but it will hold up over time.

I suspect what you really want is a class that has a number of upgradable component parts, but this will do for starters, and get you thinking the right way.

like image 137
RalphChapin Avatar answered Jan 31 '23 08:01

RalphChapin


If your intent was to replace all instances of a particular type with a subtype, then you can consider using java agents.

Using this, you would replace the base class with your enhanced class during classloading.

like image 26
Dilum Ranatunga Avatar answered Jan 31 '23 10:01

Dilum Ranatunga