A preliminary study on Java class loading mechanism _jsp programming

Source: Internet
Author: User
Tags data structures
First, after jdk1.2, class loading is done through delegates, which means that if ClassLoader cannot find the class, it requests the parent ClassLoader to perform the task, and all classloaders root is System ClassLoader, It will load the class by default-that is, from the local file system. Today we're going to explore how these mechanisms work in the JVM. Let's assume that there is a class bytecode file (such as a hello.class file), so how did he get loaded in the application and form a class object? The purpose of our article is to explain this problem.

There is a ClassLoader class in the Java.lang package, and ClassLoader's basic goal is to service the request for the class. When the JVM needs to use a class, it requests the class to ClassLoader according to its name, and then ClassLoader attempts to return a class object that represents it. You can create custom ClassLoader by overwriting methods that correspond to the different stages of the process. There is a loadclass (String name, Boolean resolve) method, which is the ClassLoader entry point. After jdk1.2, the LoadClass method will call the Findclass method by default, and the details can refer to the API documentation, and the ClassLoader we write is mainly to cover the above two methods. Back to the question we just made, how do we read the bytecode file and make it into a class object? There is a method in ClassLoader, class DefineClass (String name, byte[] B, int off, int len), and the answer is here, we base the class bytecode file (such as Hello.class) Read in a byte array, byte[] B, and convert it into a class object, which can come from files, networks, and so on, magical:

DefineClass manages many of the complexities, mysteries, and implementations of the JVM-it analyzes the bytecode into Run-time data structures, validation, and so on. Don't worry, you don't need to write it yourself. In fact, even if you want to do this, you can't overwrite it because it has been marked as final.

Some other ways:

Findsystemclass: Mount a file from a local file system. It looks for the class file in the local file system and, if it exists, converts the original byte into a class object using DefineClass to convert the file into classes.

Findclass method: This new method is invoked jdk1.2 the default implementation of LoadClass later. The purpose of Findclass is to include all of the special code for your ClassLoader, without having to replicate other code (for example, when a dedicated method fails, call system ClassLoader).

Getsystemclassloader: If you overwrite Findclass or Loadclass,getsystemclassloader, you can access the system ClassLoader with the actual ClassLoader object (rather than the fixed Findsystemclass call it).

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

Resolveclass: You can load a class without completely (without parsing), or you can load a class completely (with resolution). When writing our own loadclass, you can call Resolveclass, depending on the value of the LoadClass resolve parameter.
Findloadedclass: acts as a cache, when the request LoadClass loading class, it calls the method to see if the ClassLoader has been loaded in this class, so as to avoid reloading existing classes caused by the trouble. The method should be called first.

   second, the work flow:

1 call Findloadedclass (String) to see if a loaded class exists, and if not, use that particular magical way to get the original byte.

2 The LoadClass method is invoked through the parent class ClassLoader, and 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 LoadClass is true, then the Resolveclass parsing Class object is invoked.

5 If there is no class, return to ClassNotFoundException.

6) Otherwise, the class is returned to the calling program.

   the 三、一个 implements the ClassLoader example:

/**
*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+ "...");
Calling the system's JAVAC command
Process p=runtime.getruntime (). EXEC ("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);

This shows the presentation of the package
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);

By reading data to construct a class structure, this 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);

Returns 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 written, after compiling, we get two files:

Compilingclassloader.class,testrun.class

   Four, write an example, and then 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);
}
}

All right, run the Java testrun Hello punk.

....
....
....
Hello, punk.

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.