java - 我怎么知道一个类的实例是否已经存在于内存中?

标签 java

我如何知道一个类的实例是否已经存在于内存中?


我的问题是,如果类的实例存在,则不需要读取方法 这是我的代码

private void jButton (java.awt.event.ActionEvent evt) {
    PNLSpcMaster pnlSpc = new PNLSpcMaster();
    jtabbedPanel.addTab("reg",pnlSpc);
}

我想检查 PNLSpcMaster 的实例,当然我可以通过静态 boolean 值检查,但我认为这种方式更好。

最佳答案

如果你只想拥有一个“PNLSpcMaster”实例,那么你do need a singleton :

这是常见的单例习语:

public class PNLSpcMaster {

   /**
    * This class attribute will be the only "instance" of this class
    * It is private so none can reach it directly. 
    * And is "static" so it does not need "instances" 
    */        
   private static PNLSpcMaster instance;

   /** 
     * Constructor make private, to enforce the non-instantiation of the 
     * class. So an invocation to: new PNLSpcMaster() outside of this class
     * won't be allowed.
     */
   private PNLSpcMaster(){} // avoid instantiation.

   /**
    * This class method returns the "only" instance available for this class
    * If the instance is still null, it gets instantiated. 
    * Being a class method you can call it from anywhere and it will 
    * always return the same instance.
    */
   public static PNLSpcMaster getInstance() {
        if( instance == null ) {
            instance = new PNLSpcMaster();
        }
         return instance;
   }
   ....
 }

用法:

private void jButton (java.awt.event.ActionEvent evt) {
    // You'll get the "only" instance.        
    PNLSpcMaster pnlSpc = PNLSpcMaster.getInstace(); //<-- getInstance()
    jtabbedPanel.addTab("reg",pnlSpc);
}

或者直接:

private void jButton (java.awt.event.ActionEvent evt) {
    jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace());
}

对于基本用法,Singleton Pattern效果很好。然而,对于更复杂的用法,它可能是危险的。

您可以阅读更多相关信息:Why singletons are controversial

关于java - 我怎么知道一个类的实例是否已经存在于内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1441984/

相关文章:

java - 如何以编程方式从我的 Java 应用程序中获取内存、线程和 CPU 使用情况?

Java ConcurrentHashMap 原子获取如果存在

Java解压缩字节数组-数据检查不正确

java - 如何从 Spring Controller 在浏览器中返回 CSV 数据

java - 是否可以将按键或组件事件发送到第 3 方 swing 应用程序

即使条件不成立,Java 代码也会打印 Exception 中给出的消息

两种不同平台的Java代码运行时间差异

java - 求 pi 的值直到 50 位

Java - 使用 Socket 通过浏览器下载文件

java - Android 应用风格可在输出 APK 中包含某些文件