Implement a simple custom class loader

Source: Internet
Author: User

In the Java virtual machine, there is a class loading subsystem, which includes four kinds of loaders

1, Root loader (start class loader) 2, extended class loader 3, System class loader 4, user-defined class loader

The Genga carrier is responsible for loading the classes within the API, such as Java.lang.object

Extended class loader replication loads the classes in the EXT package in the JRE, such as C:\Program Files\java\jdk1.6.0_21\jre\lib\ext

The System class loader loads the classes in classpath, remember how we configure CLASSPATH when we configure JDK environment variables ... C:\Program Files\java\jdk1.5.0_06\lib\tools.jar; C:\Program Files\java\jdk1.5.0_06\lib\rt.jar, these are the classes inside the classpath, and the classes in your program are loaded by it because your program belongs to the current path and there is a "." In Classpath.

Add a knowledge point (pick to Baidu):

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------
Rt.jar, Dt.jar, Tool.jar are what to do, when the need to set up to Classpath?
---------------------------------------------------------------

Rt.jar is the Java base Class library, Dt.jar is a class library about the running environment, Tools.jar is the tool class library

Set in Classpath to let you import
---------------------------------------------------------------

The Web system uses Tool.jar

You use WinRAR to see what's inside.
---------------------------------------------------------------

1.
Rt.jar default in the root ClassLoader loading path inside the Claspath is superfluous
No, you can get rid of the Rt.jar in Classpath.

Then run a simple class with Java-verbose XXXX to know the JVM's system root loader path

Not only are most of the jars underneath Rt.jar jre\lib in this path.

2.

Tools.jar is used when the system is used to compile a class, which is Javac.

Javac Xxx.java

is actually running

Java-calsspath=%java_home%\lib\tools.jar Xx.xxx.Main Xxx.java

Javac is the encapsulation of the above command, so Tools.jar is not added to the classpath.

3.
Dt.jar is a class library for running environments, mainly swing packages. You'd better use swing with

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------

How does a class loader load a class?

The class loader uses the Father delegation mode to load, father Delegation mode is like this, to load a class, the first call is responsible for loading the class loader of the parent loader to try to load, if not loaded, and then throw up, throw to the root loader, if the root loader can not load, Then let the class loader, which is responsible for loading the class, load it.

The root loader does not have a parent loader, it is C implemented, so it is not available in the program, the parent loader of the extended class loader is the root loader, the parent loader of the System class loader is the extended class loader, and the user-defined class loader, by default, is the System class loader, and, of course, when customizing the class loader, is the parent loader that can be specified.

After finishing the loading sequence, we'll try to write a class loader that loads a class that is fixed somewhere


First write a class loader of your own, Myclassloader.java, inherit the ClassLoader class, and then rewrite the Findclass method:

Package com.wyp12.myClassLoader;
Import Java.io.ByteArrayOutputStream;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import java.io.IOException; /** * Write a class loader of its own, to load "d:\myclass\com\wyp12\*.class" * * @author Prince * * */public class Myclassloader extends class
	Loader {private String name;
	Public Myclassloader (String name) {super ();//class loader generated through this constructor, whose parent loader is the system class loader this.name = name; Public Myclassloader (String name, ClassLoader loader) {super (loader);//class loader generated by this constructor, the loader's parent loader is loader and if it is null, the parent adds
	The carrier inherits the parent class for the root loader//subclass, and if it does not explicitly write which constructor of the calling parent class, the THIS.name = Name of the parent class is called by default;
	Public String toString () {return this.name; //To override Findclass This method, LoadClass will call it @Override protected class<?> findclass (String name) throws
		 ption {//TODO auto-generated method stub byte[] data = null;
		FileInputStream FIS = null;
		try {fis = new FileInputStream ("d:\\myclass\\com\\wyp12\\myclassloader\\" +name+ ". Class"); } CatCH (filenotfoundexception e) {e.printstacktrace ();
		 } bytearrayoutputstream ABOs = new Bytearrayoutputstream ();
		 int ch = 0;        try {while ( -1!= (Ch=fis.read ())) {abos.write (CH);
		Writes the byte one one to the output stream} catch (IOException e) {e.printstacktrace ();   data = Abos.tobytearray (); Turn the bytes in the output stream into a byte array return This.defineclass ("Com.wyp12.myClassLoader.")
          +name,data, 0, Data.length,null); &NBSP}}
This class loader I let it load by default
D:\myclass\com\wyp12\myClassLoader
The class file under the path, the specific file name when we construct the instance then given, the following is the test classes:

Import Com.wyp12.myClassLoader.MyClassLoader;
public class Testloader {public
	static void Main (string[] args) throws Exception {myclassloader
		l1 = new MyClass Loader ("Loader1");
	 	Class DOGC = L1.loadclass ("Dog");
	 	Dogc.newinstance ();
		/*myclassloader L2 = new Myclassloader ("Loader2", L1);  Take L1 as its parent loader
		Class DOCCC = L2.loadclass ("Dog");
		Doccc.newinstance (); */
	}
}

The following is the source code of the class to be loaded, very simply to let it print out who loaded him

Package com.wyp12.myClassLoader;

public class Dog {public
Dog ()
{
System.out.println (This.getclass (). getClassLoader ()); 
      }
}


Run Result:

Loader1


The main source code for the ClassLoader is attached below:

Several of its constructor functions

Protected ClassLoader () {This
        (Checkcreateclassloader (), Getsystemclassloader ());
    }
Protected ClassLoader (ClassLoader parent) {This
        (Checkcreateclassloader (), parent);
    }
Protected ClassLoader () {This
        (Checkcreateclassloader (), Getsystemclassloader ());
    }

Converts a byte-code array into a class instance through several functions

  protected final class<?> defineclass (String name, byte[] B, int off, int len,                      protectiondomain protectiondomain)     throws classformaterror     {         return
Defineclasscond (name, B, off, Len, Protectiondomain, True);    }    //Private method w/an extra argument for skipping class verification  &nbs p;  Private Final class<?> Defineclasscond (String name,                                              byte[] B, int off , int len,                                              Protectiondomain Protectiondomain,                                              Boolean Verify)          throws Classformaterror     {    

Protectiondomain = Predefineclass (name, Protectiondomain);
    class c = null;

        String Source = defineclasssourcelocation (Protectiondomain);     try {        c = defineClass1 (name, B, off, Len, Protectiondomain, SOURC E,                               verify);    &nbsp} catch (Classformaterror CfE) {        c = Definetransformedclass ( Name, B, off, Len, Protectiondomain, CFE,                                
         source, verify);
   &nbsp     postdefineclass (c, Protectiondomain);
    return C;    }

Here's The LoadClass ()

Public class<?> loadclass (String name) throws ClassNotFoundException {return
loadclass (name, false);
protected synchronized class<?> loadclass (String name, Boolean resolve)
	throws ClassNotFoundException
    {
	///I, check if the class has already been loaded
	class C = findloadedclass (name);
	if (c = = null) {
	    try {
		if (parent!= null) {
		    c = parent.loadclass (name, false);
		} else {
		    c = findbo Otstrapclassornull (name);
		}
	    catch (ClassNotFoundException e) {
                //ClassNotFoundException thrown if class not found
                //from the Non-null pare NT class loader
            }
            if (c = null) {
	        //If still not found, then invoke Findclass into order
	        //To find th E class.
	        c = findclass (name);
	    }
	

Here's how we're going to rewrite it:

Protected class<?> Findclass (String name) throws ClassNotFoundException {
	throw new ClassNotFoundException ( name);
    

Basically so, in fact, a lot of details, because their own writing is not very good, do not write out, but to do a mark, easy to review later























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.