Java call constructor several times

I have a class that essentially resembles:

class Child extends Parent { public void reinitialize() { super(); // illegal } } 

Basically, I want to call the constructor again to reinitialize. I cannot reorganize the initialization code into my own method, because Parent is a library class, I cannot change the source.

Is there any way to do this?

+4
source share
4 answers

No, there is no way to do this. Even at the JVM bytecode level, a chain of <init> methods (constructors) can be called no more than once on any given object.

The usual answer is to reorganize the code into a regular instance method, but as you said, this is not possible.

The best you can do is find a way to redesign to get around the need for reinitialization. Alternatively, if you need certain behavior in the parent constructor, you can duplicate it yourself.

+7
source

The only job for this is either

  • create a new object every time you need to โ€œreinitializeโ€ it.
  • use delegation instead of inheritance, even if you need to use both. Using delegation, you can replace the instance.
  • Create a reinitialization method that does the same as the parent constructor. for example, replace fields or clear collections using reflections if you need to.
+3
source

One way to do this is to provide a static method that returns a new child. Alternatively, you can simply create a new child object in the client code. In any case, it looks like you cannot reuse an existing object.

+1
source

There are several ways to achieve this. One of them creates another method, for example, "init". This init method must be called either from the constructor or from the reinitialization method.

0
source

All Articles