Class loader ClassLoader and class initialization in Java

Source: Internet
Author: User
Tags access properties

Each class is compiled with a class object stored in the. class file, and the JVM uses the ClassLoader (class Loader) to load the class's bytecode file (. Class), the ClassLoader is essentially a classloader chain, in general, we only use a native ClassLoader appclassloader, which only loads trusted classes such as the Java API, usually just loaded on a local disk, These classes are generally enough for us to use. If we need to download the. Class bytecode file from a remote network or database, then we need to mount the extra ClassLoader.

In general, the ClassLoader is organized in a tree-like hierarchy, with each loader having a parent classloader. In addition, each ClassLoader supports proxy mode, that is, the loading of Java classes can be done by itself, or it can be proxied to other ClassLoader.

Several implementation classes in the ClassLoader

1, Bootstrap ClassLoader This is the JVM to load their own work required classes, fully controlled by the JVM itself, external access to this;

2, Extclassloader more special, the specific target of service in System.getproperty ("Java.ext.dirs");

3, Appclassloader, the parent class is extclassloader,java in the parameter-classpath class can be loaded by this class loader;

4, URLClassLoader, generally this class to help us achieve most of the work, the custom can inherit this class, so that only where necessary to do the modification on the line;

There are two kinds of loading order of class loaders, one is the parent class first policy, one is its own priority policy, the parent class precedence policy is a more general case (as the JDK adopts this method), under this strategy, the class will try to delegate to its parent class loader before loading a Java class, only if the parent class loader cannot find it. , just try to load the sub-class loader, if found, you do not have to load. The preferred strategy is in contrast to the parent class, which first tries to load itself, and if it does not use the parent loader to load it, it is more common in web containers (such as Tomcat) to load the parent class loader when it is not found.

Dynamic loading

Regardless of the class loader used, the class is dynamically loaded into the JVM when it is first used. This sentence has two meanings:

    1. The Java program is not necessarily fully loaded at run time, only to find the class's. class file locally or remotely, and to verify and load it (RAIGACAI), only if the class has not yet been loaded.
    2. The class is loaded when the program creates the first reference to a static member of a class, such as a static variable for a class, a static method, and a construction method-the constructor method is also static. This feature of Java is called: dynamic loading .

How the JVM loads clas files into memory

1, display loading: Not through the code of the ClassLoader call, but the JVM from the load class into memory mode;

1.1, through the class of forname;

1.2, through the ClassLoader in the LoadClass

1.3, through the Clasloader in the Findsystemclass

2, Stealth loading: Through the code ClassLoader to load the way;

How to load a class file

1) Load (Loading), executed by the ClassLoader, find bytecode, and create a class object (just create);

A) the binary data stream of the corresponding class is generated by the full name of the class. (Note that if the corresponding class file is not found, an error is thrown only when the class is actually used.) )

b) Analyze and convert these binary data streams into a specific data structure of the method area (the JVM's schema: Method area, heap, stack, local method stack, PC register) (These data structures are implementation-related, different JVMs have different implementations). Some tests are handled here, such as the validation of the magic number of the class file, checking if the file is too long or too short, and determining if there is a parent class (except for the Obecjt Class).

c) Create a Java.lang.Class instance of the corresponding class (note that with the corresponding class instance, it does not mean that the class has completed the load chain link!) )。

2) Link (linking), verify the bytecode, allocate storage space for the static domain (just allocate, do not initialize the storage space), parse the class to create the application of other classes;

A) verification (verification)

The third part of the link replaces the symbolic references of member methods, member variables, classes, and interfaces in the class with direct references, and before that, it is necessary to detect whether the referenced type correctness and access properties are correct (that is, public, private), such as checking that the final class is not inherited , check the correctness of static variables, and so on. (Note that there is actually a part of the validation process that has been performed during the loading process.) )

b) Preparation (preparation)

Allocates space for member variables of the class. Although there are initial values, they are not initialized at this time (because no Java code is executed here). As follows: All primitive types have values of 0. such as float:0f, int:0, boolean:0 (note that the boolean underlying implementation mostly uses int), and the reference type is null. It is important to note that the JVM may allocate space for some data structures that will help the program run more efficiently during this time. For example, to publish (similar to the virtual function table in C + +, see another blog post "Java: Virtual allocation and Method table of methods").

c) parsing (Resolution)

First, locate the direct reference for the symbol reference of the class, interface, method, member variable (if the symbol reference looks for the symbol first in the constant pool, and then find the type that precedes it, it will undoubtedly take more time) to complete the layout of the memory structure.

Then, this step is optional. This can be done when the symbol reference is first used, the so-called delay resolution (late resolution). However, for the user, this step is always deferred parsing, even if the runtime will execute early resolution, but the program will not show the first error when the error is thrown, but the corresponding class will be the first time the active use of the error thrown!

Finally, this step does not conflict with the class initialization that follows, and does not necessarily mean that the initialization of the class is performed until all parsing is complete. Different JVM implementations are different. See the other blog post, "Lazy initialization of Java class loading" for details.

3) initialization (initialization).

Dynamic load classes:

[HTML]View Plaincopyprint?
  1. public class Beanutilstest
  2. {
  3. public static void Main (string[] args)
  4. Throws Exception
  5. {
  6. Class clz = class.forname ("COM.AI.REDIS.A");
  7. }
  8. }
  9. Class A
  10. {
  11. public static int VALUE;
  12. Static
  13. {
  14. System.out.println ("Run parent Static code.");
  15. }
  16. }

Output Result: Print run parent static code.

Classes. Class:

[HTML]View Plaincopyprint?
  1. public class Beanutilstest
  2. {
  3. public static void Main (string[] args)
  4. Throws Exception
  5. {
  6. Class clz1 = a.class;
  7. }
  8. }
  9. Class A
  10. {
  11. public static int VALUE;
  12. Static
  13. {
  14. System.out.println ("Run parent Static code.");
  15. }
  16. }

Output: nothing.

By comparing the above, the following code should know what to print.

[HTML]View Plaincopyprint?
  1. public class Beanutilstest
  2. {
  3. public static void Main (string[] args)
  4. Throws Exception
  5. {
  6. System.out.println (A.value);
  7. }
  8. }
  9. Class A
  10. {
  11. public static final int VALUE = 10;
  12. Static
  13. {
  14. System.out.println ("Run parent Static code.");
  15. }
  16. }


Output results: 10

Someone has to ask, why not print run parent static code. Because the value variable is a constant value that has been determined at compile time with the class. class file is a reason, so do not print.

Note: The compile-time constant must meet 3 conditions: Static, Final, constant.

[HTML]View Plaincopyprint?
  1. <pre class="html" name="code"> static int A;
  2. final int b;
  3. static final int C = Math.Abs (10);
  4. static final int D;
  5. Static
  6. {
  7. d = 5;
  8. }
Ps:

< Span style= "color: #000000; Line-height:inherit; padding-top:0px; padding-bottom:0px; Font-family:inherit; Font-style:inherit; Font-variant:inherit; margin-top:0px; Margin-bottom:1.5em; Vertical-align:baseline; " >

    • 1. An interface is not instantiated, and all its elements do not have to be at the instance (object) level. Static satisfies this point.
    • 2. If the interface variable can be modified, then once a subclass implements this interface and modifies the non-final variable in the interface, and the subclass of the subclass modifies the non-final variable again, the result is that the same interface is implemented, but the value of the variable in the interface is not the same.

Above all, static final is more suitable for interfaces.

Reference:

1. Explain why interface constants can only be defined as static final through class literal constants, class loading process-thinking in Java

2, http://blog.csdn.net/biaobiaoqi/article/details/6909141

3, http://www.cnblogs.com/zhguang/p/3154584.html

4, http://iamzhongyong.iteye.com/blog/2091549

Class loader ClassLoader and class initialization in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.