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

时间:2009-09-18 00:10:04

标签: java

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


我的问题是如果存在Class的实例则不想读取方法 这是我的代码

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

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

5 个答案:

答案 0 :(得分:7)

如果您只想拥有一个“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

答案 1 :(得分:1)

我认为你是在singleton模式之后。

答案 2 :(得分:0)

没有合理的方法可以确定某个特定类的实例是否已经存在。

如果您需要知道此信息,请创建一个静态布尔字段并从构造函数中设置它:

class MyClass {
    private static bool instanceExists = false;
    public MyClass() {
        MyClass.instanceExists = true;
    }
}

答案 3 :(得分:0)

与C ++相反,有几个因素有助于在Java中获得可靠的解决方案。

以下示例不可靠,但如果您使用hasAtleastOne()方法,它可以为您提供足够正确的答案。

class Example {
    private static int noOfInstances = 0;

    public Example() {
        noOfInstances++;
    }


    public static boolean hasAtleastOne() {
        if(noOfInstances > 0)
            return true;
        else
            return false;
    }

    protected void finalize() throws Throwable {
        noOfInstances--;
    }
}

不可靠性源于这样一个事实:与C ++不同,Java中没有析构函数。垃圾收集器可以释放实例消耗的内存 - 实例仍然可以作为孤儿浮动在内存中,因为没有其他对象引用它。因此,您永远不知道是否不再引用对象。

不可否认,这在理论上与完全不在内存中有所不同,但是在确定没有类的这样的实例可用之前,你必须等待调用finalize()方法。终结器会发出警告 - 在时间关键的应用程序中不能依赖它们,因为它可能是对象孤立和最终化之间几秒到几分钟的因素;总之,不能保证可以调用它们。

处理模式

通过实施the Dispose pattern,您可以为解决方案增加更多可靠性。这还要求类的客户端调用dispose方法来发信号通知实例将被丢弃,以便可以减少实例计数。写得不好的客户会使解决方案不可靠。

答案 4 :(得分:0)

对于具有身份概念的类,Identity Map pattern适用。

相关问题