简体   繁体   中英

When static variable be instantiated in Android

For example, I have a class

public class EagerInitializedSingleton {
        private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

        public static EagerInitializedSingleton getInstance(){
            return instance;
        }
}

And my application have 2 activity A.java and B.java (from AI can go to B).
In B activity I have

import EagerInitializedSingleton.java;

public class B{
     onCreate(...){
         EagerInitializedSingleton.getInstance()...
     }
}

My question is when instantiated be instantiated`

  • When launch application (before A Activity start)
  • When import EagerInitializedSingleton.java
  • Or when EagerInitializedSingleton.getInstance()

If possible, can I check when be instantiated by write Log or something? Any help would be great appreciated.

UPDATE I'm follow here to create EagerInitializedSingleton http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
And they have say

If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections etc and we should avoid the instantiation until unless client calls the getInstance method

Like some answer say that instance be instantiated when I call EagerInitializedSingleton.getInstance()... , so who is correct?

static variables are initialized when the classloader loads the class for the first time, either through static reference or instance creation. It will be shared across all instances of the class. And remember, it will be initialized before any instance creation of the class.

So, in your question:

When launch application (before Activity start)

No

When import EagerInitializedSingleton.java

No

When EagerInitializedSingleton.getInstance()

Yes

Or whenever you make a static reference to the EagerInitializedSingleton class.

Edit - Just to clear things out as per comments:

Call to getInstance() will not result in instance creation. But the static reference to the class does as the class loads for the first time.

当您调用EagerInitializedSingleton.getInstance()

For starters, this is not a proper singleton implementation. Your constructor, or lack of one, will allow the user to use the default empty constructor and create more objects of that class. Check out how to implement it here or anywhere you find online.

The question you asked has nothing to do with android, it's a plain Java question, having to do with static variables initialization. You can find the answer to that question here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM