Preliminary exploration of Java class loading mechanism _ MySQL

Source: Internet
Author: User
1. after jdk1.2, class loading is completed through delegation. This means that if the ClassLoader cannot find the class, it will request the parent ClassLoader to execute this task, the root of all ClassLoaders is the system ClassLoader, which loads the class by default-that is, from the local file system. Today we will discuss how these mechanisms are in jvm. after JDK, class loading is done through delegation, which means that if the ClassLoader cannot find the class, it will request the parent ClassLoader to execute this task. the root of all ClassLoaders is the system ClassLoader. it will load the class by default-that is, from the local file system. Today we will discuss how these mechanisms run in jvm. Let's assume there is a class bytecode file (such as the Hello. class file). how is it loaded in the application and formed into a class object? The purpose of this article is to explain this question.

There is a ClassLoader class in the java. lang package. The basic goal of ClassLoader is to provide services for class requests. When the JVM needs to use a Class, it requests this Class from ClassLoader according to the name, and then ClassLoader tries to return a Class object that represents this Class. You can create a custom ClassLoader by overwriting methods corresponding to different stages of the process. There is a loadClass (String name, boolean resolve) method, which is the entry point of ClassLoader. after jdk1.2, the loadClass method will call the findClass method by default. for details, refer to the API documentation, the ClassLoader we wrote mainly aims to overwrite the above two methods. Back to our question, how can we read the bytecode file and make it a class object? There is a method in ClassLoader, Class defineClass (String name, byte [] B, int off, int len), the answer is here, based on the class bytecode file (such as Hello. class) read into a byte array, byte [] B, and convert it into a Class object, and the data can come from files, networks, etc., amazing :)

DefineClass manages many of the complex, mysterious, and implementation-dependent aspects of JVM-it analyzes bytecode into runtime data structures, verifies validity, and so on. Don't worry, you don't need to write it yourself. In fact, even if you want to do so, you cannot overwrite it because it has been marked as final.

Other methods:

FindSystemClass method: load files from the local file system. It looks for a Class file in the local file system. if it exists, it will use defineClass to convert the original byte to a Class object to convert the file to a Class.

FindClass method: the new method is called by the default implementation of loadClass after jdk1.2. The purpose of findClass includes all the special code of your ClassLoader without the need to copy other code (for example, when a special method fails, the system ClassLoader is called ).

GetSystemClassLoader: if it overwrites findClass or loadClass, getSystemClassLoader enables you to access the system ClassLoader with the actual ClassLoader object (instead of calling it from findSystemClass ).

GetParent: to delegate a class request to the parent ClassLoader, this new method allows the ClassLoader to obtain its parent ClassLoader. This method can be used when a custom ClassLoader cannot find a category.

ResolveClass: you can load classes not completely (without resolution), or completely (with resolution. When writing our own loadClass, you can call resolveClass, depending on the resolve parameter value of loadClass.
FindLoadedClass: acts as a cache. when loadClass is requested to load the class, it calls this method to check whether the class has been loaded. This avoids the trouble of re-loading existing classes. Call this method first.

   II. workflow:

1) Call findLoadedClass (String) to check whether a mounted class exists. if not, use the special magic method to obtain the original bytes.

2) call the loadClass method through 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 obtain the class;

4) If the resolve parameter value of loadClass is true, call resolveClass to parse the Class object.

5) If no class exists, return ClassNotFoundException.

6) Otherwise, return the class to the caller.

   3. an example of ClassLoader implementation:

* CompilingClassLoader. java
* Copyright 2005-2-12
Import java. io .*;

Public class CompilingClassLoader extends ClassLoader {
// Read the content 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 javac command of the system
Process p=runtime.getruntime(cmd.exe c ("javac" + javaFile );
Try {
// Other threads are waiting for this thread to complete
P. waitFor ();
} Catch (InterruptedException ie ){
System. out. println (ie );
Int ret = p. exitValue ();

Return ret = 0;

Public Class loadClass (String name, boolean resovle) throws ClassNotFoundException {
Class clas = null;

Clas = findLoadedClass (name );

// The package representation is described here.
String fileStub = name. replace ('.','/');

String javaFilename = fileStub + ". java ";
String classFilename = fileStub + ". class ";

File javaFile = new File (javaFilename );
File classFile = new File (classFilename );

// If a class file exists, it is not compiled.
If (javaFile. exists ()&&(! ClassFile. exists () | javaFile. lastModified ()> classFile. lastModified ())){
Try {
If (! Compile (javaFilename) |! ClassFile. exists ()){
Throw new ClassNotFoundException ("ClassNotFoundExcetpion:" + javaFilename );
} Catch (IOException ie ){
Throw new ClassNotFoundException (ie. toString ());

Try {
Byte [] raw = getBytes (classFilename );

// Construct a class structure by reading data, which is the core
Clas = defineClass (name, raw, 0, raw. length );
} Catch (IOException ie ){

If (clas = null ){
Clas = findSystemClass (name );

System. out. println ("findSystemClass:" + clas );

If (resovle & clas! = Null ){
ResolveClass (clas );

If (clas = null ){
Throw new ClassNotFoundException (name );

Return clas;
Test the loader:
* TestRun. java
* Copyright 2005-2-11
Import java. lang. reflect .*;

Public class TestRun {
Public static void main (String [] args) throws Exception {
String progClass = args [0];

String progArgs [] = new String [args. length-1];
System. arraycopy (args, 1, progArgs, 0, progArgs. length );

CompilingClassLoader ccl = new CompilingClassLoader ();

Class clas = ccl. loadClass (progClass );

// Return the type of a class
Class [] mainArgType = {(new String [0]). getClass ()};
Method main = clas. getMethod ("main", mainArgType );

Object argsArray [] = {progArgs };

Main. invoke (null, argsArray );


The above core content has been compiled. after compilation, we get two files:

CompilingClassLoader. class, TestRun. class

   4. Compile an example and run our ClassLoader

* Hello. java
Public class Hello {
Public static void main (String [] args ){
If (args. length! = 1 ){
System. err. println ("Error, exit! ");
System. exit (1 );
String name = args [0];
System. out. println ("Hello," + name );

Okay, run java TestRun Hello AFEI.

Hello, AFEI

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: 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.