Java记忆参考

我正在通过方法创建对象。然后我想“摧毁”它。我需要以某种方式记住对指定对象的引用以调用destroy()它?我该怎么做?


public class Obj {

     private int size;

     private boolean exist;


     private Obj(int size) {

          this.size = size;

          this.exist = true;

     }


     public static Obj getObj(int size) {

          Obj s = new Obj(size);

          return s;

     }


     public void destroy() {

          exist = false;

     }

}


牧羊人nacy
浏览 175回答 3
3回答

青春有我

因此,您的方法创建一个资源,其他一些实体对其进行操作,然后您释放该资源。我暖吗?在这种情况下,clean 方法是将在对象上操作的代码作为函数对象传递,因此您绝对可以在它退出时进行清理。总体思路称为“周围执行”。&nbsp;import java.util.function.Consumer;&nbsp;public static void getObj(int size, Consumer<Obj> consumer) {&nbsp; &nbsp; &nbsp; Obj s = new Obj(size);&nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; consumer.accept(s);&nbsp; &nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s.destroy();&nbsp; &nbsp; &nbsp; }&nbsp;}用于:Obj.getObj(1066, s -> {&nbsp; &nbsp; ... something with s ...;});或者,还有java.lang.AutoCloseabletry-with-resource 将责任放在调用者身上,因此最好尽可能避免。在任何情况下,尝试在静态中池化可变变量通常是一个非常糟糕的主意。

凤凰求蛊

垃圾收集器应该为你做...但是如果你想隐式调用 destroy ,你可以定义所有实例的类级别列表public class Obj {&nbsp; &nbsp; &nbsp;private int size;&nbsp; &nbsp; &nbsp;private boolean exist;&nbsp; &nbsp; &nbsp;private static List<Obj> list = new ArrayList<>();&nbsp; &nbsp; &nbsp;private Obj(int size) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.size = size;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.exist = true;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;public static Obj getObj(int size) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Obj s = new Obj(size);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.add(s) // save ref&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return s;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;public void destroy() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; exist = false;&nbsp; &nbsp; &nbsp;}}

喵喔喔

其他答案似乎试图教育您有关垃圾收集的知识。但是,为了回答您的实际问题......在你的代码,你将需要调用工厂方法和结果分配给一个变量:Obj obj = Obj.getObj(1234)。这是您对对象的引用。当您想调用该destroy()方法时,请使用该引用。例如:public class Main {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Obj obj = Obj.getObj(42);&nbsp; &nbsp; &nbsp; &nbsp; obj.destroy();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java