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();
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.
It is better to set null or use new Object()
obj = null;
or
obj = new Object();
The garbage collector will clear the object finally
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With