如何在Java中重置当前对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20386444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:34:10  来源:igfitidea点击:

How to reset current object in Java?

javaobjectthisreset

提问by user2519990

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

如果我有一个 Foo 类型的对象 myObject,而在 myObject 中,有没有办法重置自身并再次运行构造函数?

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

我知道以下内容不起作用,但可能有助于传达这个想法。

this = new Foo();

回答by talnicolas

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

只需编写一个方法来“重置”对象的所有变量(null 或 0 或默认值)。

回答by dasblinkenlight

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 nulland numeric fields to zero; your resetmethod needs to set them all explicitly.

注意:您的重置方法需要设置所有字段,而不仅仅是您通常在构造函数中设置的字段。例如,您的构造函数可以依赖于默认将引用字段初始化null为零,并将数字字段初始化为零;您的reset方法需要明确设置它们。

回答by Alex Vulaj

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

为您的类存储一组默认值或状态。然后编写一个reset()方法来恢复类中的所有这些默认值。

public void reset(){
    // Reset everything to your default values
}

回答by Robin Green

An alternative approach, which is gaining in popularity because it tends to make code easier to reason about, is to make your objects immutable, and instead of changing their state (e.g. resetting them), simply create a new object.

另一种方法越来越受欢迎,因为它往往使代码更容易推理,是使您的对象不可变,而不是更改它们的状态(例如重置它们),只需创建一个新对象。

回答by Mohamed Abdullah J

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

最好设置 null 或使用 new Object()

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

The garbage collector will clear the object finally

垃圾收集器最终会清除对象

回答by Mohamed Abdullah J

@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)
          {

          }
     }}