N
N
Noortvel2016-10-30 20:48:51
Java
Noortvel, 2016-10-30 20:48:51

Is it possible to replace an object with a new one, along with replacing links?

Is it possible to replace an object with a new one, along with the replacement of links? That is, so that the links would refer to a new object.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vamp, 2016-11-01
@Noortvel

This is possible if you use a proxy object. That is, all links in the program will look at the proxy object, which encapsulates a link directly to the object that you want to replace.

// MyClass - тип объекта, который хотим подменить
// унаследоваться необходимо, чтобы не сломать совместимость типов
class MyProxy extends MyClass {

  // наш спрятанный объект, который будем заменять в будущем
  private MyClass hidden;

  @Override
  public int hashCode() {
    return hidden.hashCode();
  }

  @Override
  public boolean equals(Object o) {
    return hidden.equals(o);
  }
  // и так далее заоверрайдить все-все публичные
  // методы наследуемого класса

  // правда, с публичными свойствами будет проблема - для
  // их замены необходима более сложная логика:
  @Override
  public int calculate() {
    hidden.var = var; // на случай если поле было изменено извне
    int result = hidden.calculate();
    var = hidden.var; // а это если поле было изменено изнутри
    return result;
  }

  public int var;

  // а вот и главный заменщик
  void setObject(MyClass new_o) {
    hidden = new_o;
    var = new_o.var;
  }
}

Then it remains only to find all the places where the object is created and replace it with a proxy object. Next, the real object is replaced by a call to setObject().
If the proxied object has final fields or methods, then you will have to abandon the inheritance of MyClass and replace the reference type of MyClass with MyProxy throughout the project.

F
FoxInSox, 2016-10-30
@FoxInSox

Certainly:

Object objectA = new Object();
Object objectB = new Object();
objectA = objectB;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question