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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1441984/
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-10-29 16:33:25  来源:igfitidea点击:

How can I know whether an instance of a class already exists in memory?

java

提问by Jeus

How can I know whether an instance of a class already exists in memory?

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



My problem is that don't want read method if exist instance of Class this is my code

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

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

I want check instance of PNLSpcMasterof course I can check by static boolean but I think this way is better.

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

回答by OscarRyz

If you want to have only one instance of "PNLSpcMaster" then you do need a singleton:

如果您只想拥有一个“PNLSpcMaster”实例,那么您确实需要一个单例

This is the common singleton idiom:

这是常见的单例习惯用法:

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;
   }
   ....
 }

Usage:

用法:

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

Or directly:

或者直接:

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

For basic usages the Singleton Patternworks very well. However for more sophisticated usages it may be dangerous.

对于基本用法,单例模式非常有效。然而,对于更复杂的用法,它可能是危险的。

You could read more about it: Why singletons are controversial

您可以阅读更多相关信息:为什么单身人士有争议

回答by Andrew

I think you're after the singletonpattern.

我认为你在追求单例模式。

回答by Vineet Reynolds

Several factors would contribute to obtaining a reliable solution in Java, as opposed to C++.

有几个因素有助于在 Java 中获得可靠的解决方案,而不是 C++。

The following example is unreliable, although it could provide you with a correct enoughanswer if you use the hasAtleastOne() method.

以下示例不可靠,但如果您使用 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--;
    }
}

The unreliability stems out of the fact that destructors are not available in Java, unlike C++. It is upto the garbage collector to release the memory consumed by an instance - the instance could still be floating in memory as an orphan since no other object references it. Hence, you never know whether an object is no longer being referenced.

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

Admittedly, that is theoretically different from being absent in memory at all, but you will have to wait for the finalize() method to be called before you know for sure that no such instance of the class is available. Finalizers come with a warning - they are not to be relied upon in time-critical applications, since it could be a factor of a few seconds to minutes between object orphaning and finalization; in short there is no guarantee that they could be called.

诚然,这在理论上与完全不存在于内存中不同,但是您必须等待调用 finalize() 方法,然后才能确定该类的此类实例不可用。终结器带有一个警告——在时间关键的应用程序中不要依赖它们,因为它可能是对象孤立和终结之间的几秒到几分钟的因素;简而言之,不能保证可以调用它们。

The Dispose Pattern

处置模式

You could add more reliability to the solution by implementing the Dispose pattern. This also requires the client of the class to invoke the dispose method to signal that the instance is to be disposed off, so that the instance count can be reduced. Poorly written clients will make the solution unreliable.

您可以通过实施Dispose 模式为解决方案增加更多的可靠性。这也需要类的客户端调用 dispose 方法来通知实例将被释放,从而可以减少实例计数。写得不好的客户将使解决方案不可靠。

回答by John Rayner

For classes that have a notion of identity, the Identity Map patternapplies.

对于具有标识概念的类,适用标识映射模式

回答by Igor ostrovsky

There isn't a reasonable way to find out whether or not an instance of a particular class already exists.

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

If you need to know this information, create a static boolean field and set it from the constructor:

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

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