Classloader learning Summary

Source: Internet
Author: User
Document directory
  • Source: http://grid-qian.javaeye.com/blog/139561
Source: http://grid-qian.javaeye.com/blog/139561classloaderlearning Summary

Keyword: classloader

I didn't expect my summary to be sent after so long. Work is very busy, and children are a little busy, so they can't do anything at home. So it took so long. In fact, there are many articles about classloader on the Internet, so there is no need to submit another article. However, I will write another article on my own later. The first is a summary of your own learning, and the second is to give you an extra angle to learn classloader. First, let's list my reference articles. There are too many articles related to the Internet. After reading these articles for a long time, you can find them. The first is the two series of articles on the most important IBM developwork. I think this technology website of IBM is doing a great job. Many articles are a good helper for learning. I like to search for any problems. There are several other good articles, including Robbin. There is also a classic book deep into JVM. It is recommended that you have time to study Java. Http://www.ibm.com/developerworks/cn/java/j-dclp1/

Http://www.ibm.com/developerworks/cn/java/j-dyn0429/

Http://www.javaeye.com/topic/136427

Http://www.javaeye.com/topic/11? Page = 1

Http://www.jdon.com/article/15456.html

Http://blog.bcchinese.net/shiaohuazhang/archive/2004/10/13/2715.aspx-basic knowledge of classloader we need to go through a complex process to get a class that can be used in JVM from a class file. First, JVM loads a Java class type through the classloader mechanism, connects it, And then initializes it. Load --> connect (verify --> prepare --> resolve) --> initialize. After such a process, we can get a Java class that can be used in JVM. The connection includes verification, preparation, and resolution. The following figure shows the process. It was taken from IBM's article, so it was in English. Sorry.

Loading is to read the binary Java type into JVM. It provides a very basic memory structure for class objects. According to the definition of Java API: The Class Loader is the object responsible for loading the class.ClassloaderA class is an abstract class. If the binary name of a given class is specified, the Class Loader attempts to find or generate data that constitutes the class definition. The general policy is to convert the name to a file name, and then read the "class file" of the name from the file system ". Each class object contains a pairClassloader. Array classClassThe object is not created by the class loader, but automatically created as needed during Java runtime. The class loader of the array class is composed of class. getclassloader () returns the same class loader as its element type. If the element type is basic, there is no class loader for this array class.

The load consists of three basic actions: 1. Generate a binary data stream representing this type using the fully qualified name of this type. 2. parse this binary data stream into the internal data structure of the method area. 3. Create a Java data stream representing this type. lang. class class instances JVM classloader can load Java classes in two ways. One is to load classes in advance, and the other is to load classes in use. However, no matter whether it is pre-loaded or re-loaded, errors during the loading process are reported only when the class is actively used for the first time in the program: linkageerror. If this class has never been used, no errors will be reported. The connection is to merge the binary data that has been read into the running state of the JVM. Verify that the Java data format is correct and applicable to JVM. Prepare to allocate the memory required for this type. The parsing function converts the symbol reference in the constant pool into a direct reference. Parsing this step can be postponed until the program uses this symbol to parse it. Initialization is performed when the JVM actively uses this type for the first time after the connection. Active use involves the following situations: when creating a new instance of the class (New commands or through ambiguous creation, reflection, cloning, or deserialization) when calling static methods of a class, use static fields of the class or assign values to this field (except static fields modified by final) when initializing a subclass of a class, the initialization of A Class marked as a startup class at JVM startup requires that its superclass be initialized first, but for interfaces, this is not the case. This interface is initialized only when the non-constant field declared in the interface is used. In other words, do not require the superclass to be initialized first during interface initialization. In the preparation phase, JVM allocates memory for class variables and sets the default initial value. This default value is the default value of Java for each type. In the initialization phase, the class variable is assigned a real initial value. This initial value is the initial value of the class variable specified by the programmer during programming. When a class has a superclass, it first initializes this superclass. After initialization, the program can call the static method of the class or create an instance of the class in the static field of the category class. Through the connection, you can convert the symbol reference of the class into a direct reference. In this case, check the correctness and permissions. The dynamic scalability of the Java language is embodied in the connection process. Java programs can determine the connection type at runtime. In this way, the dynamic scalability of Java is realized. There are two methods: one is to use the forname () method of Java. Lang. Class; the other is to use the loadclass () method of the User-Defined class loader. The advantage of the first method is that it must be loaded and initialized. The second method is not necessarily initialized. However, the second method is more flexible and can implement some specific functions. For example, security or loading certain types such as those downloaded from the Internet. Each classloader maintains its own namespace. In the same namespace, the names of two classes cannot be the same. The namespace consists of all classes that use this loader as the founding class loader. The two classes of different namespaces are invisible, but you can still access the classes of another namespace as long as you get the reference of the Class Object corresponding to the class. To implement the Class Loader security mechanism at the top layer of the Java Security Sandbox Model, classloader adopts the parent-parent delegation model. (Java Security Sandbox mechanism is introduced in the previous article about classloader preparation)

One example is to test the classloader of your JVM.

Java code
  1. /* Loadersample1.java */
  2. Public class loadersample1 {
  3. Public static void main (string [] ARGs ){
  4. Class C;
  5. Classloader Cl;
  6. CL = classloader. getsystemclassloader ();
  7. System. Out. println (CL );
  8. While (CL! = NULL ){
  9. CL = Cl. getparent ();
  10. System. Out. println (CL );
  11. }
  12. Try {
  13. C = Class. forname ("Java. Lang. Object ");
  14. CL = C. getclassloader ();
  15. System. Out. println ("Java. Lang. Object's loader is" + Cl );
  16. C = Class. forname ("loadersample1 ");
  17. CL = C. getclassloader ();
  18. System. Out. println ("loadersample1's loader is" + Cl );
  19. } Catch (exception e ){
  20. E. printstacktrace ();
  21. }
  22. }
  23. }

Running result on my machine (Sun Java 1.4.2)

sun.misc.Launcher$AppClassLoader@1a0c10fsun.misc.Launcher$ExtClassLoader@e2eec8null java.lang.Object's loader is nullLoaderSample1's loader is sun.misc.Launcher$AppClassLoader@1a0c10f

The first line indicates that the system class loader is instantiated from the sun. Misc. launcher $ appclassloader class.

The second line indicates that the parent of the system class loader is instantiated from the sun. Misc. launcher $ extclassloader class.

The third line indicates that the parent of the system class loader is Bootstrap.

The fourth line indicates that the core class java. Lang. object is loaded by bootstrap.

Another example demonstrates how a namespace class uses another namespace class. In this example, loadersample2 is loaded by the system class loader and loadersample3 is loaded by the custom loader. The two classes are not in the same namespace, however, loadersample2 obtains the reference of the Class Object corresponding to loadersample3, so it can access public members (such as age) in loadersampl3 ). Run: Java loadersample2

Java code
 
 
  1. /* Loadersample2.java */
  2. Import java.net .*;
  3. Import java. Lang. Reflect .*;
  4. Public class loadersample2 {
  5. Public static void main (string [] ARGs ){
  6. Try {
  7. String Path = system. getproperty ("user. dir ");
  8. URL [] US = {new URL ("file: //" + path + "/SUB /")};
  9. Classloader loader = new urlclassloader (US );
  10. Class C = loader. loadclass ("loadersample3 ");
  11. Object o = C. newinstance ();
  12. Field F = C. getfield ("Age ");
  13. Int age = f. getint (O );
  14. System. Out. println ("Age is" + age );
  15. } Catch (exception e ){
  16. E. printstacktrace ();
  17. }
  18. }
  19. }
  20. /* Loadersample3.java */
  21. Public class loadersample3 {
  22. Static {
  23. System. Out. println ("loadersample3 loaded ");
  24. }
  25. Public int age = 30;
  26. }

Loadersample3 loaded age is 30

From the running results, we can see that in class loadersample2, you can create an object in class loadersample3 of another namespace and access its public member age.

Ii. classloader implementation mechanism the Class Loader adopts the parent-parent delegation model. You can specify the parent when creating a custom class loader. If not specified, the system class loader is used as its parent by default. If null is passed to the User-Defined loader constructor, the bootstrap loader is both parent and parent. Classloader sequentially searches for classes from the cache, parent and parent. Classloader first checks whether the class to be loaded is the same as the class to be loaded in the past. If they are the same, the class returned last time is returned (that is, the class stored in the cache ). If not, give the parent class the opportunity to load the class. The two steps are recursively repeated in depth-first mode. If the parent class returns NULL (or throwsClassNotFoundException), Then the class loader will find the class source in its own path. Because the parent class loader always gets the opportunity to load the class first, the class loaded by the classloader is closest to the root. This means that all core boot classes are loaded by the boot loader, which ensures that the classes are loaded (for examplejava.lang.Object. This also allows the class loader to see the class loaded by itself, its parent class, or its ancestor, but not the class loaded by its children.

Unlike other class loaders, the bootstrap Class Loader (also known as the primordial Class Loader) cannot be instantiated by Java code. (Usually because it is implemented as part of the VM itself .) This class loader can load the core system class from the started class path, usually the JAR file located in the JRE/lib directory. But can be used-XbootclasspathModify the class path using the command line option (described later ). The extension class loader (also known as the standard extension class loader) is a child of the bootstrap class loader. It is mainly responsible for loading classes from the extended directory, usually located in the JRE/lib/EXT directory. This provides simple access to new extensions. For example, different security extensions can be implemented without modifying the user's class path. The system class loader (also called the application Class Loader) is responsibleCLASSPATHCode for loading the path specified by the environment variable. By default, this class loader is the parent class of any Class Loader created by the user. This is alsoClassLoader.getSystemClassLoader()Class Loader returned by the method. The following table shows the path of the three class loaders:

Command line options Explanation Class loaders involved
-Xbootclasspath: <used; or: separated directories and zip/jar files> Set the search path for the bootstrap class and resource. Guide
-Xbootclasspath/A: <used; or: separated directories and zip/jar files> Add the path to the end of the startup class path. Guide
-Xbootclasspath/P: <used; or: separated directories and zip/jar files> Add the path to the front of the startup class path. Guide
-Dibm. JVM. bootclasspath = <used; or: separated directories and zip/jar files> The value of this attribute is used as an additional search path and inserted-Xbootclasspath/p:-Xbootclasspath:The value defined by the option. Between the defined value and the startup class path. The startup path or default value, or Guide
-Djava. Ext. dirs = <use; or: separated directories and zip/jar files> Specify the search path for extension classes and resources. Extension
-CP or-classpath <with; or: separated directories and zip/jar files> Set the search path for application classes and resources. System
-Djava. Class. Path = <used; or: separated directories and zip/jar files> Set the search path for application classes and resources. System

3. Some JVM parameters provide debugging information for classloader. Based on this information, we can understand important information in the class loading process, which is helpful for us to analyze and study the class loading process. In actual work, I only encountered a linkageerror related error example. To analyze this error, I used the-verbose JVM parameter. When JVM is started, this parameter is used to generate a large number of loaded classes when the virtual machine runs the program. We can learn where the classes are loaded into the JVM. If you want more detailed information, you can set the-verbose: Class parameter. As for more related parameters or JVM-specific parameters provided by IBM, I have not used them in detail. You can refer to the subsequent sections in the first reference series of this article.

Four related exceptions I still want to write some related examples. Haha, I want to come and find that there are no examples in the first reference series, so I will not write them, you can check it on the IBM website. Http://www.ibm.com/developerworks/cn/java/j-dclp2.htmlThis section briefly introduces related exceptions or errors, includingClassNotFoundException,NoClassDefFoundError,ClassCastException,UnsatisfiedLinkError,ClassCircularityError,ClassFormatError,Predictionininitializer. The first three may be common, and the last four may not be easy to see.

ExceptionInInitializer: If the initialization is suddenly completed, some exceptions are thrown.EAndEIs notErrorOr a subclass of it, it will be createdExceptionInInitializerErrorClass, andEReplace this instance as a parameterE. If a Java Virtual Machine attempts to create a classExceptionInInitializerErrorBut becauseOut-Of-Memory-ErrorIf a new instance cannot be createdOutOfMemoryErrorObject.

ClassFormatError: Specifies that the binary data format of the requested compilation class or interface is incorrect. This exception is thrown during the verification of the link phase of the class loading. If the bytecode is changed, for example, the primary or secondary version number is changed, the binary data format is incorrect. For example, if the bytecode is intentionally changed or an error occurs when a file is transmitted over the network, this exception may occur. The only way to fix this problem is to get the correct copy of the bytecode and may need to be re-compiled.

ClassCircularityError: A class or interface cannot be loaded because it is its own superclass or superinterface. It is actually loop inheritance. A-> B, B->.

UnsatisfiedLinkError: When searching for local methods, the required definition is not found in the class path.

Classcastexception: too common.

ClassNotFoundException,Noclassdeffounderror: also common. Let's talk about their differences here. When the former is explicitly loaded, the exception thrown by the required class cannot be found in the class path. when the latter is implicitly loaded, the exception thrown by the required class cannot be found in the class path. Explicit and implicit definitions are described earlier.

4. Note: When the class loader is used to load the class, the Class Loader assumes that the path not ending with/points to the JAR file; the path ending with a slash points to a directory. The Parent-parent delegation mode of the Class Loader. The visible range of each class loader only includes itself, its parent and its ancestor. That is to say, it cannot see its sub-loader loaded class. Load the loadclass () method to implement your own class loader. Note the following when using the non-parent delegation mode: all classes in the program must be in the class path of the loader, including Java. lang. object.

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.