Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset current object in Java?

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();
like image 807
user2519990 Avatar asked Dec 04 '13 21:12

user2519990


2 Answers

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.

like image 60
Sergey Kalinichenko Avatar answered Oct 10 '22 06:10

Sergey Kalinichenko


It is better to set null or use new Object()

obj = null;
   or
obj = new Object();

The garbage collector will clear the object finally

like image 6
Mohamed Abdullah J Avatar answered Oct 10 '22 08:10

Mohamed Abdullah J