Description of the Java class loader ClassLoader

Source: Internet
Author: User
Tags user definition

(1) The contents of the API document are as follows:

The class loader is the object that is responsible for loading the class. The ClassLoader class is an abstract class. If a binary name is given to a class, the ClassLoader attempts to find or generate the data that makes up the class definition. The general strategy is to convert the name to a file name and then read the class file for that name from the file system.

Each Class object contains a reference to the ClassLoader that defines it.

The class object of an array class is not created by the ClassLoader, but is created automatically by the Java runtime as needed. The class loader for an array class is returned by Class.getclassloader (), which is the same as the class loader of its element type, and if the element type is a base type, the array class has no classloader.

Applications need to implement ClassLoader subclasses to extend the way that Java virtual machines load classes dynamically.

The class loader is typically used by the security manager to indicate a security domain.

The ClassLoader class uses a delegate model to search for classes and resources. Each ClassLoader instance has a related parent class loader. When you need to find a class or resource, the ClassLoader practice delegates the task of searching for a class or resource to its parent ClassLoader before attempting to find the class or resource yourself. The built-in ClassLoader for a virtual machine (called "Bootstrap class loader") does not have a parent classloader in itself, but it can be used as the parent ClassLoader for ClassLoader instances.

Typically, Java virtual machines load classes from the local file system in a platform-related manner. For example, in a UNIX system, a virtual machine loads a class from a directory defined by the CLASSPATH environment variable.

However, some classes may not originate from a file; they may originate from other sources, such as networks, or they may be constructed by an application. The DefineClass method converts a byte array to an instance of class. An instance of this newly defined class can be created using class.newinstance.

The methods and construction methods of objects created by the ClassLoader can reference other classes. To determine the referenced class, the Java virtual machine calls the LoadClass method that originally created the class loader for the class.

For example, an application can create a network class loader to download class files from the server. The sample code looks like this:

ClassLoader loader = new Networkclassloader (host, Port);
Object main = Loader.loadclass ("main", true). Newinstance ();
...
The network ClassLoader subclass must define methods Findclass and loadClassData to implement the load class from the network. After you download the bytes that make up the class, it should use method DefineClass to create the class instance. The example implementation is as follows:

 class NetworkClassLoader extends ClassLoader {     String host;     int port;     public Class findClass(String name) {         byte[] b = loadClassData(name);         return defineClass(name, b, 0, b.length);     }     private byte[] loadClassData(String name) {         // load the class data from the connection          . . .     } }

Binary name
As defined in Java Language specification, any class name passed as a String parameter to a method in ClassLoader must be a binary name.

Examples of valid class names include:

"Java.lang.String"
"Javax.swing.JSpinner DeF auLTE d IToR""Java.seCuRITy .K ey S ToRe Builder F ILeBuILd eR 1 "
"Java.net.URLClassLoader 3 1 "

(2) Why to use ClassLoader

/****** below is a reference to someone else's blog as a learning note ***************/
http://www.iteye.com/topic/83978

ClassLoader A word that often appears and discourages many people, this article will try to explain the ClassLoader in the most obvious way, hoping to play a little role in the friends who do not understand the mechanism.

To learn more about ClassLoader, you first need to know what ClassLoader is used for, as the name implies, it is used to load class files to the JVM for use by the program. We know that Java programs can dynamically load class definitions, and this dynamic loading mechanism is implemented through ClassLoader, so it is conceivable how important classloader is.

Seeing here, perhaps some friends will think of a problem, that is, since ClassLoader is used to load the class into the JVM, then how is ClassLoader loaded? Is it not a Java class?

No mistake, there is really a classloader not written in the Java language, but a part of the JVM implementation, this ClassLoader is bootstrap ClassLoader (startup ClassLoader), This classloader loads the Java core API to meet the most basic needs of Java programs while the JVM is running, including user-defined ClassLoader, where the so-called user definition refers to ClassLoader implemented through Java programs, One is Extclassloader, this classloader is used to load the Java extension API, that is,/lib/ext class, one is Appclassloader, This classloader is used to load the class in the Classpath settings directory on the user's machine, and typically the programmer's custom class is loaded by the ClassLoader without specifying ClassLoader.

When running a program, the JVM starts, runs Bootstrap ClassLoader, and the ClassLoader loads the Java Core API (Extclassloader and Appclassloader are also loaded at this time), Then call Extclassloader to load the extension API, and finally Appclassloader load the class defined in the Classpath directory, which is the most basic loading process for a program.

The above probably explained the role of ClassLoader and a most basic loading process, next will explain the way classloader load, here you have to say classloader here using the parental delegate mode for class loading.

Each custom ClassLoader must inherit the abstract class ClassLoader, and each ClassLoader will have a parent ClassLoader, We can take a look at ClassLoader. This abstract class has a getparent () method, which is used to return the parent of the current ClassLoader, noting that the parent is not referring to the inherited class, Instead, a classloader is specified when the ClassLoader is instantiated, and if the parent is null, then the parent of the ClassLoader is the bootstrap ClassLoader by default. What's the use of this parent?

We can consider a situation where we have customized a clientdefclassloader, We use this custom ClassLoader to load the java.lang.String, so will the String be loaded by this classloader? In fact java.lang.String This class is not loaded by this clientdefclassloader, but is loaded by bootstrap ClassLoader, why is this? This is actually the reason for the parental delegate mode, because before any custom ClassLoader loads a class, it will first delegate its father ClassLoader to load, and only if the Father ClassLoader is unable to load successfully, will it be loaded by himself, In the above example, Because Java.lang.String is a class that belongs to the Java Core API, when loading it with Clientdefclassloader, the ClassLoader will first delegate its father ClassLoader to load, as mentioned above, when ClassLoader's When the parent is null, the parent of ClassLoader is Bootstrap ClassLoader, so the topmost layer of ClassLoader is bootstrap ClassLoader, So when the final delegate is Bootstrap ClassLoader, bootstrap ClassLoader returns the String class.

Let's take a look at some of the source code in ClassLoader:
Java Code Collection Code

   protected synchronizedClassLoadClass(String name,BooleanResolvethrowsclassnotfoundexception {//First check whether the class specified by the name has been loadedClass C = findloadedclass (name);if(c = =NULL) {Try{if(Parent! =NULL) {//If parent is not NULL, the loadclass of parent is called to loadc= Parent.loadclass (name,false); }Else{//parent is null, the Bootstrapclassloader is called to loadc = FINDBOOTSTRAPCLASS0 (name); }      }Catch(ClassNotFoundException e) {//If it still fails to load successfully, call its own findclass to loadc = findclass (name); }  }if(resolve)  {Resolveclass (c); }returnC }

From the code above, we can see that the approximate process of loading a class is the same as the example I gave earlier, and when we implement a custom class, we only need to implement the Findclass method.

Why use this parental trust model?

The first reason is that this avoids repeated loading, and when the father has loaded the class, there is no need for the ClassLoader to be loaded again.

The second reason is that given the security factor, let's just imagine that if we don't use this delegate pattern, we can use a custom string to dynamically replace the defined type in the Java Core API at any time, so there's a very big security risk, and the way that parents delegate, you can avoid this situation, Because the string has already been loaded at startup, the user-defined class is unable to load a custom ClassLoader.

Above the classloader of the loading mechanism is introduced, and then have to explain the other and ClassLoader related classes, that is class, each ClassLoader loaded class file, It will eventually be referenced by programmers as instances of class classes, and we can think of class as a template for ordinary classes, where the JVM generates corresponding instances based on this template, which is eventually used by programmers.

We see that there is a static method in class Forname, and this method is the same as the purpose of the LoadClass method in ClassLoader, which is used to load class, but the two are different in function.
Class

Description of the Java class loader ClassLoader

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.