ClassLoader specific explanations in Java

Source: Internet
Author: User

java. java files are compiled in the future, the number encyclopedia will generate class files. class file keyword mining tool. The class file is sent to the hard disk as a binary byte code. When we need to use or load the Java file into the JVM, the byte-code class file is read from the hard disk, and then the class file is loaded into the JVM by the ClassLoader. That is, all of the Java files are loaded into the JVM by the ClassLoader. Of course, the class loader is also a Java file. So how does the first ClassLoader load into the JVM? At the start of the JVM, a local approach is dispatched Findbootstrapclass method loads the initial classloader,private native Class Findbootstrapclass (String name), This local approach is written in C + +.

1. The system already has 3 varieties loader

1.1 Booststrapclassloader (boot) loads Rt.jar the following class (this loader is written in C + +, which is usually not visible in development)

1.2 Extclassloader Load Extclassloader The following class (the jar below the Ext folder)

1.3 Appclassloader Load Classpaht the following class

The classes we write are simply loaded into the JVM by appclassloader the loader.

2. Loading mechanism of class loader (parental trust mechanism)

Each classloader has a corresponding parentclassloader.

2.1 The parent-child relationship of the system ClassLoader

The father of the self-definition classloader is Appclassloader

Appclassloader's father is Extclassloader.

Extclassloader's father is Booststrapclassloader.

Java Code Preservation Code

public class Testclassloader {

public static void Main (string[] args) {

The class loader of the target at that time

ClassLoader loader = new Testclassloader (). GetClass (). getClassLoader ();

From the time the target ClassLoader wanted to find his ancestors.

while (loader! = null) {

System.out.println (Loader.getclass (). GetName ());

Loader = Loader.getparent ();

}

Know that finding the ultimate ancestor is null

SYSTEM.OUT.PRINTLN (loader);

}

}

Output:

Sun.misc.launcher$appclassloader

Sun.misc.launcher$extclassloader

Null

2.2 Class Loader load order

The ClassLoader is loaded down from the root

That is boot-"Exiclassloader-" Appclassloader

When a class requirement is loaded, it is first passed by the Appclassloader loader to its dad Extclassloader, and then Extclassloader passes it to his father, boot.

When boot finds that his load scale has a corresponding class, it is loaded into the JVM, or handed to the son Extclassloader disposal.

Extclassloader again in his load scale class to find there is no corresponding class, there is loaded into the JVM, did not hand over to the appclassloader disposition.

Appclassloader again in the classpath path to find the corresponding class, found on the load, no report abnormal.

Reason: This ensures that one of the classname in the JVM corresponds to the same class, because it is loaded down from the root.

Avoid repeated loading, when the father has now loaded the class of cent, there is no need for the child classloader to load again.

If you load from the bottom up, you can cause a certain classname to correspond to several classes in the JVM. Can we define the class loader and the size of the load from each.

When classes loaded from a defined class are found in their respective sizes, they can all be loaded, causing a classname in the JVM to correspond to several different classes

2.3 For example, we have to define a class loader to load the Java.lang.String class, then we can not reach our goal.

Because the loading mechanism is loaded from top to bottom, when passed to the boot above, it is now loaded into the JVM, it is not our custom class loader to load it.

However, we must be able to customize a class loader to load the classes we specify.

3. How to customize a class load

First of all, we need to inherit Classloadar

Then, we can not destroy the original class loading mechanism (parental trust mechanism), so we can not cover up the LoadClass method, we need to cover up the Findclass method.

Finally, the code for our ClassLoader is written in the Findclass method.

View Source Commentary:

Java Code Preservation Code

Protected Class loadclass (String name, Boolean resolve)

Throws ClassNotFoundException

{

Synchronized (Getclassloadinglock (name)) {

First look at the name of the class is not now loaded

Class C = findloadedclass (name);

If it is not loaded

if (c = = null) {

Long T0 = System.nanotime ();

Quiz to get Parentclassloader to load

try {

if (parent! = NULL) {

When parent is not NULL, let parent go to LoadClass

c = Parent.loadclass (name, false);

} else {

When the parent is null, the local method is dispatched

c = findbootstrapclassornull (name);

}

} catch (ClassNotFoundException e) {

}

When the Parentclassloader does not load the cent

if (c = = null) {

Long T1 = System.nanotime ();

Dispatching Findclass method to load

c = findclass (name);

}

}

-Indexread arguments from command-line "http://www.shoudashou.com"

-Indexread arguments from command-line "http://www.4lunwen.cn"

-Indexread arguments from command-line "http://www.zx1234.cn"

-Indexread arguments from command-line "http://www.penbar.cn"

-Indexread arguments from command-line "http://www.whathappy.cn"

-Indexread arguments from command-line "Http://www.lunjin.net"

-Indexread arguments from command-line "http://www.ssstyle.cn"

-Indexread arguments from command-line "http://www.91fish.cn"

-Indexread arguments from command-line "http://www.fanselang.com"

if (resolve) {

Resolveclass (c);

}

return C;

}

}

4. For example

Goal: Self-Define a class loader plus we specify the way to pass through my encryption class.

Process: Locate the class file under the specified path, decrypt it, and load it into the JVM.

4.1 Define a class that requires an encrypted compilation, and use it for testing

Java Code Preservation Code

public class MyClass extends Date {

@Override

Public String toString () {

Return "Hello World";

}

}

4.2 Encrypt the original class file

Java Code Preservation Code

public static void Main (string[] args) throws Exception {

String inputsrc = args[0];//The path and file name of the original class file

String outputsrc = args[1];//Encrypted file paths and filenames for future storage

FileInputStream fis = new FileInputStream (INPUTSRC);

FileOutputStream fos = new FileOutputStream (OUTPUTSRC);

Calling the encryption algorithm

Cypher (FIS, FOS);

Fis.close ();

Fos.close ();

}

/**

* Cryptographic decryption Function method

*

* @param is

* @param os

* @throws IOException

*/

private static void Cypher (InputStream is, OutputStream os) throws IOException {

int b =-1;

while ((b = Is.read ())! =-1) {

Set 0 to 1 and 10% to 0

Os.write (b ^ 0xff);

}

}

4.3 Write our own class loader

Java Code Preservation Code

public class Myclassloader extends ClassLoader {

The path to the class to load

Private String classsrc;

Public Myclassloader () {

}

Public Myclassloader (String classsrc) {

THIS.CLASSSRC = CLASSSRC;

}

@Override

Protected Class Findclass (String name) throws ClassNotFoundException {

Find the location of the encrypted class file from the first

String classfielname = classsrc + "\ \" + Name + ". Class";

try {

FileInputStream fis = new FileInputStream (classfielname);

Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();

Allocation and decryption algorithm

Cypher (FIS, BAOs);

Fis.close ();

byte[] bytes = Baos.tobytearray ();

Converts the read-out binary to a class byte code

return defineclass (null, Bytes, 0, bytes.length);

} catch (Exception e) {

E.printstacktrace ();

}

return Super.findclass (name);

}

}

4.4 Use our own class to load and load our encrypted classes into the JVM.

Java Code Preservation Code

The first class loader to load our encrypted class file

Note that this local loading class should be the way we encrypt future files.

Class clazz = new Myclassloader ("E:/allworkspace/workspace1/classloadertest/bin/com/gusi/test"). LoadClass ("MyClass ");

After reflection, test our ClassLoader.

Date date = (date) clazz.newinstance ();

System.out.println (Date.tostring ());

 

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.