On Java class loading mechanism

Source: Internet
Author: User

Preliminary study Java class loading mechanism

First, injdk1.2later, class loading is done through a delegate, which means that ifClassLoaderthe class could not be found, it would request the parentClassLoaderto perform this task, allclassloadersThe root is the systemClassLoader, it loads the class in the default way-- that is, from the local file system. Today we are going to discuss theJVMhow these mechanisms work. Let's assume that there is aclassbyte-code files (such asHello.classfile), then in the application, how did he get loaded in and form a class object? Our purpose in this article is to explain the problem.

in theJava.langthere's one in the bag.ClassLoaderclass,ClassLoaderThe basic goal is to service the request of a class. WhenJVMwhen you need to use a class, it is based on the nameClassLoaderrequest this class, and thenClassLoaderattempt to return a class that represents theClassobject. By overriding the methods that correspond to the different stages of this process, you can create a customClassLoader. One of them has aloadclass (String name, Boolean resolve)method, which is theClassLoaderthe entry point, injdk1.2later,LoadClassmethod will call the defaultFindclassmethod, detailed information can be consultedAPIdocument that we have writtenClassLoaderThe main purpose is to cover the above two methods. Back to our question just now, how to read into a bytecode file and make it into a class object? In theClassLoaderThere's a way,Class defineclass (String name, byte[] B, int off, int len)The answer is here, and we're going toclassbyte-code files, such asHello.class)read into a byte array,byte[] B,and turn it intoClassobjects, and this data can be derived from files, networks, etc., Magic Bar:)

DefineClass manages Many of the complexities, mysteries, and implementations of the JVM - It parses bytecode into run-time data structures, verifies validity, and so on. Don't worry, you don't have to write it yourself. In fact, even if you want to do this, you cannot overwrite it because it has been marked as final.

Some other methods:

Findsystemclass Method: Loads the file from the local file system. It looks for the class file in the local file system and, if it exists, uses defineclass to convert the raw bytes to a class object to convert the file into classes.

Findclass method: This new method is called by the default implementation of jdk1.2 after LoadClass. The use of Findclass contains all the special code for your ClassLoader , and there is no need to copy other code (for example, when a specialized method fails, calling the system ClassLoader).

Getsystemclassloader: If you overwrite findclass or loadclass, Getsystemclassloader allows you to access the system with actual ClassLoader objects ClassLoader (instead of a fixed call to it from findsystemclass ).

GetParent: In order to delegate a class request to the parent ClassLoader, this new method allows ClassLoader to get its parent ClassLoader. This method can be used when a custom ClassLoader cannot find a class using a special method.

Resolveclass: The class can be loaded either completely (without parsing), or it can be loaded completely (with parsing). When writing our own loadclass , you can call resolveclass, depending on loadclass 's Resolve the value of the parameter.

Findloadedclass: acts as a cache , and when the request loadclass loads the class, it calls the method to view Whether the ClassLoader has been loaded into this class avoids the hassle of reloading existing classes. The method should be called first.

second, the work flow:

1) call findloadedclass (String) to see if there is a loaded class , and if not, take that special magical way to get the raw bytes.

2) Call the loadclass methodthrough the parent class ClassLoader , if the parent class ClassLoader is NULL , the class is loaded by default, that is, the system ClassLoader .

3) Call Findclass (String) to find the class and get the class;

4) If the value of the resolve parameter of the loadclass is true, then the call Resolveclass Parse Class object .

5) If there are no classes, return to classnotfoundexception.

6) Otherwise, return the class to the calling program.

a city implements the examples of ClassLoader:

/**

*compilingclassloader.java

*copyright 2005-2-12

*/

Import java.io.*;

public class Compilingclassloader extends classloader{

read the contents of a file

Private byte[] GetBytes (String filename) throws ioexception{

File File=new file (filename);

Long Len=file.length ();

Byte[] raw=new byte[(int) Len];

FileInputStream fin=new fileinputstream (file);

int R=fin.read (RAW);

if (r!=len) throw new IOException ("Can ' t read all," +r+ "! =" +len);

Fin.close ();

return raw;

}

Private Boolean compile (String javafile) throws ioexception{

System.out.println ("ccl:compiling" +javafile+ "...");

call the system's javac command

Process p=runtime.getruntime (). EXEC ("Javac" +javafile);

try{

other threads are waiting for this thread to complete

P.wait


On Java class loading mechanism

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.