Java Dynamic Loading

Source: Internet
Author: User
Part 1: Some actions on class loading during startup of Java Virtual MachineWhen you use Java programname. Class to run the program, Java finds JRE, then JVM. dll, and loads the dynamic library into the memory. This is the JVM. Load other dynamic libraries and activate JVM. After the JVM is activated, Initialization is performed and bootstraploader is generated. The class loader is written by C ++. Bootstraploader loads the extclassloader in launcher. Java and sets its parent to null, which means that the parent class loader of extclassloader is bootstraploader. Then bootstraploader loads
Appclassloade and set its parent class loader to extclassloader. However, if you call the getparent () method of extclassloader, null is returned. Both class loaders exist in the form of static classes and are written in Java. These three class loaders all have their own class search path: bootstraploader: Sun. boot. class. pathextclassloader: Java. ext. dirsappclassloader: Java. class. the preceding three paths are system attributes of Java. getproperty (string key) method to view its settings: system. out. println (system. getproperty ("Java. class. path "); now we can look at the output values of each attribute to find out which classes each class loader is responsible for: Key: Sun. boot. class. pathstring: % java_home %/lib/resources. jar, Rt. jar, sunrsasign. jar, JSSE. jar, JCE. jar, Chars ETS. jar, % java_home %/classes key: Java. ext. dirsstring: % java_home %/lib/EXT, % WINDOWS %/Sun/Java/lib/EXT key: Java. class. pathstring: Specifies the directory where the program's entry file class is located. bootstraploader is responsible for the Java core class (all. ). Extclassloader is responsible for loading extension classes (so classes starting with javax. * And classes under the ext directory exist ). Appclassloader is responsible for loading the class of the application itself. Part 2: Java class loading mechanism. The process of loading classes in Java.Based on the loading time, automatic loading is divided into two types: pre-loading and on-demand loading. Pre-loaded classes are started after the JVM starts and before the application runs. Contains at least all classes in rt. jar. On-demand loading is performed after the application is running. During the running process, the JVM encounters a class that has not been loaded. At this time, the Class Loader loads the class into the memory. Classes are loaded in two ways: Implicit loading and explicit loading. Implicit loading uses the new method. During class initialization, the JVM loads classes according to the corresponding class loader. Explicit loading means that the programmer explicitly loads classes using a class loader in the code. The JVM auto-load class algorithm is as follows: if the instance of Class A references the instance of Class B, by default, JVM will first find the class loader of Class, then use the class loader to load Class B. The general algorithm of the Class Loader loading class is as follows: Background: Class Loader is organized according to hierarchies, and each class loader has a parent. If the parent class loader is not explicitly specified when the class loader is created, JVM will specify the system class loader as the parent of the class loader. Each class loader has its own loaded class cache. In other words, loaded class Cache consists of two parts: classloader and class name loaded by it.
  1. Check whether the class has been loaded.
  2. If the class has not been loaded, call the parent object to load the class.
  3. If the parent object cannot be loaded, call findclass () of the object to obtain the class.
Therefore, when creating your own class loader, you only need to overload the findclass () method. After Java 1.2, classes are loaded in the delegate mode.

A loaded class cannot be updated. If you try to use the same classloader to load the same class again, an exception occurs in Java. Lang. linkageerror: duplicate class definition. You can only create a new classloader instance to load the new class again.

  Part 3: define your own class loaderWhy should I use my classloader?
Because the built-in classloader of JVM only knows how to load standard Java class files from the local file system. If you write your own classloader, you can
  1. Automatically verifies the digital signature before executing the untrusted code
  2. Dynamically create custom build classes that meet specific user needs
  3. Obtain Java classes from a specific place, such as databases and networks.

When creating your own classloader, you must inherit java. Lang. classloader or its subclass. When instantiating each classloader object, you must specify a parent object. If not, the system automatically specifies classloader. getsystemclassloader () as the parent object.

Part 4: display several methods of loading and instantiating classes in the program: 1) Use class Foo = Class. forname (string classtypename); // call classloa der. getcallerclassloader () obtains the current class loader, and then finds and loads classtypename. Orclass Foo = Class. forname (string classtypename, Boolean initialize, classloader loader) // explicitly specifies which class loader is used to find and load classtypename. Classtypename boo = (classtypename) Foo. newinstance (); 2) Load classes based on the classloader subclass, such as java.net. urlclassloader. Method for obtaining the current classloader: classloader Foo = thread. currenttread (). getcoontextclassloader ();

Part 5: Difference between class. forname () and classloader. loadclass () 

Class clazz = Class. forname ("XXX. XXX ");
And
Classloader Cl = thread. currentthread (). getcontextclassloader ();
Class clazz = Cl. loadclass ("XXX. XXX ");
Can all load a class. What is their difference?
Further study: class. forname () is called
Class. forname (name, initialize, loader); that is, class. forname ("XXX. XXX "); equivalent to class. forname ("XXX. XXX ", true, callclass. class. getclassloader ());

The second parameter indicates whether to initialize the class when loading the class, that is, to call the Statement of the static block of the class and to initialize the static member variable.

Class clazz = Cl. loadclass ("XXX. XXX"); the initialization option is not specified. Class can be initialized only when clazz. newinstance (); is executed. It can be said that the execution process of class. forname ("XXX. XXX", false, Cl) is consistent. Only classloader. loadclass () is a baseline operation.

Let's take a look at the JDBC driver loading.
Class. forname ("com. MySQL. JDBC. Driver ");
Connection conn = drivermanager. getconnection ("jdbcurl ");
When class. forname ("com. MySQL. JDBC. Driver") is called, the driver has been initialized and registered to drivermanager. MySQL driver code
Public class driver extends nonregisteringdriver
Implements java. SQL. Driver
{

Public Driver ()
Throws sqlexception
{
}

Static
{
Try
{
Drivermanager. registerdriver (New Driver ());
}
Catch (sqlexception E)
{
Throw new runtimeexception ("can't register driver! ");
}
}
}
Modify JDBC driver Loading
Classloader Cl = thread. currentthread (). getcontextclassloader ();
Class clazz = Cl. loadclass ("com. MySQL. JDBC. Driver ");
Clazz. newinstance ();
Connection conn = drivermanager. getconnection ("jdbcurl ");
It can also be executed.

Further speaking:

Class. forname is used to load classes from the specified classloader. If this parameter is not specified, classes are loaded from the classloader where the current object instance is loaded.
The classloader instance calls the loadclass method, which refers to the class called from the current classloader instance,This instance may not be the same as the classloader that loads the current class instance..
For example, there are two classloader A, B, and C. the instance of the currently running Class D is D (it is loaded as a), if class is used in D. for forname, The classloader used is a. Of course, it can also be specified as B. if the classloader instance found by the code in D is C, it is to use d to load the specified class.

Why use different classloader for loading?
For example, if you want to use your class loader to perform specific operations during the class loading process, use the classloader method.

The bytecode generation framework, such as cglib, uses the special classloader method in many places.
It is common to use multiple classloader, such as our app server. their classloader is different between the web and EJB, so as to avoid mutual interference of the class loading between the two.

Another example:
When is the static initialization block called?
Public A {static {system. Out. println ("hahaha ");}}
Class. forname ("");
Class. forname ("A", false, classloader. getsystemclassloader ());
What is the secret? What is the mechanism and principle of Java classloader?
Program example:
Public Class {
Static {system. Out. println ("A' static is executed! ");}
Public A () {system. Out. println ("A' construct is executed! ");}
Public void show () {system. Out. println ("A' method is executed! ");}
}
Caller 1:
Class C = Class. forname ("");
Method M = C. getmethod ("show", new class [0]);
System. Out. println ("A' test is executed! ");
Object OBJ = C. newinstance ();
M. Invoke (OBJ, new object [0]);
Execution result:
A' static is executed!
A' test is executed!
A' construct is executed!
A' method is executed!
Caller 2:
Class C = classloader. getsystemclassloader (). loadclass ("");
System. Out. println ("A' test is executed! ");
Method M = C. getmethod ("show", new class [0]);
Object OBJ = C. newinstance ();
M. Invoke (OBJ, new object [0]);
Execution result:
A' test is executed!
A' static is executed!
A' construct is executed!
A' method is executed!
It can be seen that the execution sequence is to execute the code in the static {} block, then execute the constructor, and then call the method.
Classloader can be loaded in two ways:
1) pre-loading: load the base class
2) Load-on-demand load as needed
Java dynamically loads class in two ways:
1) implic it is implicit, that is, the feature loaded only by instantiation is used to dynamically load the class
2) The explicit mode of explicit mode can be either of the following two methods:
A) forname () method of Java. Lang. Class (this method is used for loading the call program 1)
B) The loadclass () method of Java. Lang. classloader (this method is used to load the above call Program 2)
When will the static block be executed?
Executed when forname (string) is called to load class,(This process is recursively called in all parent classes of the class)
If classloader. loadclass is called, it will not be executed.
Forname (string, false, classloader) is not executed.
If the static block is not executed when the class is loaded, the. New, class. newinstance () operation is executed during the first instantiation.
The static block is executed only once.

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.