class loader for Java ClassLoader

Source: Internet
Author: User
Tags object object

Class executes three steps before execution: load-and-connect initialization

Loading of classes in 1.java

Java class loading refers to reading the binary data in the class's. class file into memory, placing it in the method area of the run-time data area, and then creating a class object in the heap to encapsulate the data structure of the class in the method area. The class of the heap area can be understood as a mirror of the method area, corresponding to the data structure of the class of the method area, and the invocation of classes is realized through this mirror.

There are several ways to load a. class file:

1. Loading directly from the local system

2. Download the. class file over the network

3. Download the. class file from Zip,jar

4. Extract the. class file from a proprietary database

5. Dynamically compile the Java source file into a. class file

The end result of class loading is to generate a class object that is located in the heap, which encapsulates the data structure of the class within the method area, and provides the Java programmer with an interface to access the data structures within the method area

View source The class object can only be created by a Java virtual machine and its constructors are privatized



2. Connect

1. Verify: Ensure that the class being loaded is correct (primarily to prevent the disgusting class file from being loaded)

2. Prepare: Allocate memory for static variables of the class and initialize them to default values

3. Parsing: Converting a conforming reference in a class to a direct reference

3. Initialization

Assigning the correct initial value to a static variable of a class

All Java Virtual machine implementations must be initialized when each class or interface is "first actively used" by a Java program.

Java's use of classes is divided into: active use, passive use

Active use of six kinds: (except for these 6 kinds, the other is passive use)

1. To create an instance of a class

2. Access static variables for a class or interface or assign a value to the static variable

3. To invoke a static method of a class

4. Reflection

5. Initializes subclasses of a class

6. Classes that are labeled to start classes when the Java Virtual machine is started

4. Class Loader ClassLoader

Class loader type

1.java class loader with virtual machine:

-----Root Class Loader Bootstrap

The ClassLoader does not have a parent classloader, it is responsible for loading the virtual machine's core class library, such as java.lang.String, and so on, the root classloader is used to load the class when the JVM is started, so that the JVM can work properly, so it is implemented with native (c + +) code, was first created, at the lowest level. It does not inherit the Java.lang.ClassLoader class.

-----Extension Class Loader extension

The class loader's parent class loader is the root class loader. It gets the load class library from the directory specified by the Java.ext.dirs system properties or loads the class library from the Jre\lib\ext subdirectory of the JDK's installation directory. If the jar is placed in this directory, it will also be automatically loaded with the extension classloader. The extension ClassLoader is a Java class and is a subclass of the Java.lang.ClassLoader class

-----system ClassLoader

Also becomes the application ClassLoader, its parent classloader is the extension classloader, it will load the directory and jar files configured in Classpath, it is the default parent classloader of the user-defined ClassLoader, the system ClassLoader is the Java class, the subclass of the Java.lang.ClassLoader class

2. User-defined class loader: is a subclass of Java.lang.ClassLoader, you can define the class loader

Class loader mechanism

The class loader is used to load the class into the Java virtual machine, and the class loading process uses the Father's delegation mechanism , which can ensure the security of the Java platform, because the user-defined class loader cannot load the reliable class that should be loaded by the parent loader in this mechanism. such as java.lang.String is always loaded by the root ClassLoader. In this delegation mechanism, in addition to the root classloader of Java, the rest of the loaders have only one parent loader.

Custom Class Loaders

The user-defined class loader needs to satisfy the parent delegate mechanism, which is the default system ClassLoader for its parent. To implement a custom loader, you only need to integrate the ClassLoader class and then overwrite the Findclass (String name) method, which specifies the name of the load class according to the parameter, and returns a reference to the corresponding class object

Custom class Loader class: Myclassloader

  1. Package com.longpo.classloader;

  2. Import Java.io.File;

  3. Import Java.io.FileInputStream;

  4. Import java.io.FileNotFoundException;

  5. Import java.io.IOException;

  6. Import Java.io.InputStream;

  7. Public class Myclassloader extends ClassLoader {

  8. private String name; //class loader name

  9. private String path="d:\\"; //Load the path of the class

  10. Private final String type=". Class"; //class file extension

  11. Public Myclassloader (String name)

  12. {

  13. super ();

  14. This.name=name;

  15. }

  16. //Specify parent class loader

  17. Public Myclassloader (ClassLoader parent, String name)

  18. {

  19. super (parent); //display Specifies the loader's parent loader

  20. This.name=name;

  21. }

  22. //Set the path of the load class

  23. Public String GetPath () {

  24. return path;

  25. }

  26. public void SetPath (String path) {

  27. This.path = path;

  28. }

  29. @Override

  30. Public String toString () {

  31. return "Myclassloader:" + name;

  32. }

  33. //Read binary data of the corresponding class file---Simple read here

  34. private byte[] loadClassData (String name)

  35. {

  36. //Find the corresponding file according to the class name to be loaded

  37. Name=name.replace (".", "\ \"); The Com.longpo.test directory structure is \ \

  38. File file=new file (Path+name+type);

  39. //Create byte array based on file size

  40. byte[]bytes=New byte[(int) file.length ()];

  41. try {

  42. InputStream is = new FileInputStream (file);

  43. int Len=is.read (bytes); //Returns the length of the read byte

  44. Is.close ();

  45. } catch (FileNotFoundException e) {

  46. E.printstacktrace ();

  47. } catch (IOException e) {

  48. E.printstacktrace ();

  49. }

  50. return bytes;

  51. }

  52. //Be sure to override this method

  53. @Override

  54. Public class<?> Findclass (String name) throws ClassNotFoundException {

  55. //Get binary data for class file

  56. byte[]data=loadclassdata (name);

  57. return this.defineclass (name, data, 0,data.length); Returns a reference to a class object

  58. }

  59. }



Define a Test load class: Simple

    1. Package com.longpo.classloader;

    2. Public class Simple {

    3. Public Simple ()

    4. {

    5. System.out.println ("Simple class loader name is:" +This.getclass (). getClassLoader ());

    6. }

    7. }

Testing a custom load class: Test

  1. Package com.longpo.classloader;

  2. Public class Test {

  3. public static void Main (string[] args) throws exception{

  4. //loader1 's parent loader defaults to the system loader--plus the system loader, the extension loader, the root loader

  5. Myclassloader loader1=New Myclassloader ("Loader1");

  6. Loader1.setpath ("d:\\lib\\loader1\\"); Loader1 Load Path

  7. //loader2 's parent loader is loader1--with loader1 loader, system loader, extension loader, root loader

  8. Myclassloader loader2=New Myclassloader (Loader1,"Loader2");

  9. Loader2.setpath ("d:\\lib\\loader2\\"); Loader2 Load Path

  10. //loader3 's parent loader is NULL, which is the root loader--only the root loader above

  11. Myclassloader loader3=New Myclassloader (null,"Loader3");

  12. Loader3.setpath ("d:\\lib\\loader3\\"); Loader3 Load Path

  13. Test (LOADER2);

  14. Test (LOADER3);

  15. }

  16. public static void Test (ClassLoader loader)throws exception{

  17. Class Clazz=loader.loadclass ("com.longpo.classloader.Simple"); Loadclas will automatically call the Findclass method

  18. Object object=clazz.newinstance ();

  19. }

  20. }

At this point, the compiled class file is sent to the folder of the corresponding loader directory, I use Eclipse, you can find the. class file in the bin directory of the project's directory.

Run test at Eclipse to get the result:



The relationship of each loader is



When using Loader2 to load simple, according to the Father delegation mechanism, will start from the root loader to try to load, continue to load, the way the System class loader loaded successfully. Use Loader3 to load simple, according to the Father delegation mechanism, first loaded by the root loader, loading failed to have loader3 themselves loaded

Original Address http://techfoxbbs.com/blog-1-2.html

class loader for Java ClassLoader

Related Article

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.