Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Call constructor multiple times

Tags:

java

I have a class that's essentially like:

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

Basically, I want to call the constructor again to reinitialize. I can't refactor out the initialization code into its own method, because Parent is a library class I can't modify the source of.

Is there a way to do this?

like image 426
Xodarap Avatar asked Dec 21 '22 12:12

Xodarap


1 Answers

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

The usual answer is to refactor the code out into a normal instance method, but as you said, this is impossible.

The best you can do is to find a way to redesign to get around the need for reinitialization. Alternatively, if there's a specific behavior in the parent constructor you need, you might be able to duplicate it yourself.

like image 163
Antimony Avatar answered Jan 02 '23 04:01

Antimony