What happens when java program starts?

后端 未结 4 1386
予麋鹿
予麋鹿 2021-02-02 02:42

Recently have been touched Java classloaders and suddenly recognized that do not fully understand what happens step-by-step when someone calls

j         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-02-02 03:32

    The decision is made by the classloader. There are different implementations, some of which pre-load all classes they can and some only loading classes as they are needed.

    A class only needs to be loaded when it is accessed from the program code for the first time; this access may be the instantiation of an object from that class or access to one of its static members. Usually, the default classloader will lazily load classes when they are needed.

    Some classes cannot be relied on to be pre-loaded in any case however: Classes accessed via Class.forName(...) may not be determined until this code is actually exectued.

    Among other options, for simple experiments, you can use static initializer code to have a look at the actual time and order in which classes are actually loaded; this code will be executed when the class is loaded for the first time; example:

    class SomeClass {
    
        static {
            System.out.println("Class SomeClass was initialized.");
        }
    
        public SomeClass() {
            ...
        }
    
        ...
    
    }
    

提交回复
热议问题