How to reset current object in Java?
java, object, reset, this
Solution
There is no way to run a constructor again on an existing instance. However, you can organize your code in a way to allow resetting with a minimum amount of work, like this:
public class MyClass {
public MyClass() {
reset();
}
public void reset() {
// Setup the instance
this.field1 = ...
this.field2 = ...
}
}
Note: your reset method needs to set all fields, not just the ones that you usually set in the constructor. For example, your constructor can rely upon the default initialization of reference fields to `null` and numeric fields to zero; your `reset` method needs to set them all explicitly.
Problem
If I have an object myObject of type Foo, while inside myObject, is there a way to reset itself and run the constructor again? I know the following does not work, but might help convey the idea. ``` this = new Foo(); ```