How to reset the current object in Java?

If I have a myObject of type Foo, and inside myObject, is there a way to reset and run the constructor again?

I know that the following does not work, but may help convey the idea.

this = new Foo(); 
+6
source share
6 answers

Cannot start the constructor again in an existing instance. However, you can organize your code in such a way that you can perform a reset with a minimum amount of work, for example:

 public class MyClass { public MyClass() { reset(); } public void reset() { // Setup the instance this.field1 = ... this.field2 = ... } } 

Note. Your reset method needs to set all the fields, not the ones you usually set in the constructor. For example, your constructor may rely on initializing the default fields to null and number fields to zero; your reset method needs to explicitly set them.

+12
source

Better to set to null or use a new Object ()

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

The garbage collector will clear the object finally

+4
source

An alternative approach, which is gaining popularity because it seeks to make the code more understandable, is to make your objects immutable, and instead of changing their state (for example, resetting them), simply create a new object.

+2
source

Just write a method that will "reset" with all the variables of your object (null or 0 or the default value).

+1
source

You have a set of default values ​​or states for your class stored inside it. Then write a reset() method that will restore all of these defaults to the class.

 public void reset(){ // Reset everything to your default values } 
+1
source
 @SuppressWarnings({ "unchecked" }) static void emptyObject(Object obj) { Class c1 = obj.getClass(); Field[] fields = c1.getDeclaredFields(); for(Field field : fields) { try { if(field.getType().getCanonicalName() == "boolean") { field.set(obj, false); } else if(field.getType().getCanonicalName() == "char") { field.set(obj, '\u0000'); } else if((field.getType().isPrimitive())) { field.set(obj, 0); } else { field.set(obj, null); } } catch(Exception ex) { } }} 
0
source

Source: https://habr.com/ru/post/959345/


All Articles