1. Class Loader definition1.1 Class Loader Overview:
Java class loading is done by the virtual machine, the virtual machine to describe the class file loaded into memory, and data validation, parsing and initialization, the final form can be used directly by the Java Virtual Machine Java type, which is the virtual machine class loading mechanism. The specific implementation of this function in the JVM is the classloader . The classloader reads the. class bytecode file to convert it to an instance of the Java.lang.Class class. Each instance is used to represent a Java class. Through the newinstance of the instance () method to create an object of that class.
life cycle of class 1.2:
The life cycle of classes from loading to virtual machine memory to being freed from memory is as follows:
load : "Load" is a phase of the class loading process, and the functions that are completed in this phase are:
Gets the binary byte stream that defines this class through the fully qualified name of the class
Transforms the static storage structure represented by this binary byte stream into the runtime data structure of the method area
The Java.lang.Class object that represents this class is generated in memory as the class accesses the mouth.
validation : The first step in the connection phase. The purpose of the verification is to ensure that the information in the byte stream of the class file conforms to the requirements of the virtual machine and does not compromise the security of the virtual machine so that the virtual machine is protected against malicious code. Roughly complete the following four check actions:
File Format Verification
Source data validation
BYTE code Verification
Symbol Reference Validation
Preparation : The second step in the connection phase is to formally allocate memory for the class variable and set the initial value of the variable. (Contains only class variables and does not contain instance variables).
parsing : The third step in the connection phase, the virtual machine replaces the symbolic reference in the constant pool with a direct reference, and the parsing action is primarily for classes or interfaces, fields, class methods, method types, and so on.
initialization : The initialization of a class is the last step in the class loading process, in which the Java program code defined in the class is actually started. This phase executes the class constructor.
use : Use the functionality provided by this class.
unload : Release from memory.
the role of Class 1.3 loaders
Loading of classes
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 Java.lang.Class object of this class in the heap that encapsulates the class's objects in the method area class. Look at the picture below
The end product loaded by the class is a class object that is located in the heap area
Javamore than one ClassLoader can be installed in a virtual machine, the system defaults to three main class loaders, each classresponsible forload a class at a specific location:Bootstrap,extclassloader,appclassloaderThe class loader is alsoJavaclass, because the others areJavaClass loader itself is also loaded by the ClassLoader, it is clear that the first ClassLoader is not aJavaclass, which is exactly whatBootStrap. Javaall Class loaders in a virtual machine are organized in a tree with a parent-child relationship, and when you instantiate each class loader object, you need to specify a parent class loader object or
The System class loader is used by default
Loaded for its parent class.
1.4 Get the class file path:Java classes can be dynamically loaded into memory, which is a major feature of Java, also known as runtime binding, or dynamic binding.
1. Reading from a ZIP package is common and eventually becomes the basis for future jar,war,ear formats.
2. Obtained from the network, this scenario is typical of the applet.
3. Runtime compute generation, typical scenario is Java Dynamic Agent technology.
4. Generated from other files, a typical scenario is a JSP application that generates a corresponding class class from a JSP file.
1.5 Java.lang.ClassLoader class Overview:The ClassLoader class is defined in the Chinese document as follows:
The introduction of the ClassLoader class from the documentation summarizes the function of this class to find the corresponding class bytecode file based on the fully qualified name of a specified class, and then load it into an instance of the Java.lang.Class class.
Class 1.6 Loader partitioning:Most Java programs use the following 3 system-provided ClassLoader:
Start the class loader (Bootstrap ClassLoader):
This classloader is responsible for loading the class library in the <java_home>\lib directory into the virtual machine memory, which is used to load the Java core Library, which does not inherit from Java.lang.ClassLoader and cannot be called directly by a Java program. The code is written in C + +. Is part of the virtual machine itself.
Extension class loader (extendsion ClassLoader):
This classloader is responsible for loading the class library under the <java_home>\lib\ext directory, which is used to load the JAVA extension library, and developers can use the ClassLoader directly.
Application class loader (application ClassLoader):
This classloader is responsible for loading the class library under the user classpath (CLASSPATH), which is typically loaded by this classloader, which is the return value of the Getsystemclassloader () method in the ClassLoader. This is also known as the system ClassLoader. Typically this is the default class loader for the system.
In addition, we can add our own defined ClassLoader to meet special requirements and inherit the Java.lang.ClassLoader class.
the hierarchical relationships between class loaders are as follows:
look at the class loader using code:
Package com.wang.test; Public class Testclassloader { publicstaticvoid main (string[] args) { = Testclassloader. class . getClassLoader (); System.out.println (Loader.tostring ()); System.out.println (Loader.getparent (). toString ()); System.out.println (Loader.getparent (). GetParent ());} }
To observe the printed result:
[Email protected]
[Email protected]
Null
The first line prints the Application class loader (the default loader), the second line prints its parent classloader, the extension classloader, according to our idea the third line should print the startup ClassLoader, and here it returns NULL, because GetParent (), return null, The Startup class loader is used as the parent loader by default.
2. Delegate mechanism of class loader
The parental delegation model is a specification of the relationship between the organization ClassLoader, and he works by:
If a class loader receives a request for a class load, it does not attempt to load the class itself, but instead delegates the request to the parent ClassLoader to complete, so that the layer is progressive,
Eventually all load requests are uploaded to the topmost startup ClassLoader, and only when the parent ClassLoader fails to complete the load request (it does not find the required class in its search scope).
Before handing it over to the subclass loader to try to load.
The benefit is that the Java class has a hierarchical relationship with precedence along with its classloader. This is necessary, such as Java.langobject, which is stored in the \jre\lib\rt.jar,
It is the parent class of all Java classes, so no matter which class is loaded to load the class, eventually all load requests are rolled up to the top-level startup ClassLoader, so the object class is loaded by the startup ClassLoader.
So loading is the same class, if you do not use the parent delegation model, by the various classloader to load themselves, there will be more than one object class in the system, the application will be all messed up.
whenJavawhen a virtual device loads a class, which ClassLoader does it send to load? the class loader of the current thread is first loaded to load the first class in a thread. if the classAThe class is referenced in theB,Javathe virtual machine will use the load classAclass loader to load the classB. you can also call directlyClassloader.loadclass ()method to specify a class loader to load a class. each class loader loads a class and then delegates it to its parent class loader. when all ancestor class loaders are not loaded into the class, go back to the initiator ClassLoader and not load, then throwclassnotfoundexception, not to find the son of the initiator ClassLoader, because there is noGetchildmethod, even if there is, there are many sons, which one to find?
each ClassLoader only classes in specific locations and directories can be loaded by themselves, but they may delegate other class loaders to load classes, which is the class loader's delegate mode. class loader-Level delegation to the BootStrap class loader, when BootStrap cannot load the class that is currently being loaded, and then rolls back to the descendant class loader for a true load. When you fall back to the original class loader, you should report the classnotfoundexception exception if it cannot complete the load of the class itself .
There is an interview, can you write a class called Java.lang.System , in order not to let us write System class, class loading takes a delegate mechanism, which ensures that dads are always first-in-the-same class that dads can find, always using Java System-Provided System .
Add the previously written class to the JDK of the Rt.jar , what kind of effect will it have? No !!! seems to be unable to arbitrarily class file added into Rt.jar in the file
Class.forName () and Classloader.loadclass ():class.forname (): Is a static method, the most commonly used is Class.forName (String className); Returns a class object based on the fully qualified name of the passed-in class. The method performs initialization of the class while loading the class file into memory. such as:class.forname ("Com.wang.HelloWorld");
Classloader.loadclass (): This is an instance method that requires a ClassLoader object to invoke the method, which loads the class file into memory and does not perform initialization of classes. This class is not initialized until it is first used. The method requires a ClassLoader object, so you can specify which class loader to use as needed.
such as:ClassLoader cl= ...; Cl.loadclass ("Com.wang.HelloWorld");
Interview questions:
Can you write a class called Java.lang.System to replace the System class provided by Java?
No, because the class loads the delegate mechanism, the parent loader will first look for the class, as found on the load.
3. Write your own class loaderKnowledge Explanation:1. The custom class loader must inheritClassLoader2. Rewrite FindclassMethodcall DefineClass in 3.findClass MethodProgramming Steps:Write a program that simply encrypts the contents of the file. a class loader of its own is written to load and decrypt encrypted classes. Write a program that calls the ClassLoader load class and cannot define reference variables with the class name in the source program because the compiler does not recognize the class. The program can be used in addition to usingClassloader.loadmethod, you can also use the context class loader that sets the thread, or the System class loader, and then use theClass.forName. Experimental steps:for non-package namesclassfiles are encrypted, and the encrypted results are stored in another directory, for example:java myclassloader mytest.classf:\itcastRun the Load class program, the result can be loaded normally, but the printed class loader name isAppclassloader:java myclassloader MyTest F:\itcastReplace with the encrypted class fileCLASSPATHenvironment of the class file, and then perform the previous operation is a problem, error description isAppclassloaderThe class loader load failed. DeleteCLASSPATHenvironment of the class file, and then perform the previous operation is no problem.
importjava.io.*;importjava.lang.reflect.*;p Ublicclass Myclassloader extends classloader{private String path = null; Public Myclassloader (String path) throwsexception//checks if the file exists {file F = new file (path); if (!f.isdirectory ()) {throw new RuntimeException (path + "IsNot a directory"); } This.path = path; The public Class findclass (String name)//throwsexception//Why cannot throw {try {File F = newFile (path,name.substring (name). LastIndexOf ('. ') +1) + ". Class"); FileInputStream fis = new FileInputStream (f); Bytearrayoutputstream BOS = Newbytearrayoutputstream (); Cypher (Fis,bos); byte [] buf = Bos.tobytearray (); Fis.close (); Bos.close (); return DefineClass (name,buf,0,buf.length); }catch (Exception e) {throw new ClassNotFoundException (name + "is not found!"); } return null; } public static void Cypher (Inputstreamistream,outputstream ostream) throws Exception {//The following code may encounter 255 bytes, as Byte is 1 /*byte B = 0; while ((b = (byte) istream.read ())! =-1) {ostream.write (b ^ 0XFF); }*/int b = 0; while ((b = Istream.read ())! =-1) {Ostream.write ((byte) b) ^ 0xff); }} public static void Main (String [] args) throwsexception {///below omits error checking if (!args[0].endswith ("class")) {Classloa Der Loader = Newmyclassloader (args[1]); Class cls = Loader.loadclass (Args[0]); /* Let the custom class inherit the date Class System.out.println (Cls.getclassloader (). GetClass (). GetName ()); Java.util.Date d = (java.util.Date) cls.newinstance (); System.out.println (D.tostring ()); *///method M =cls.getmethod ("test", null);//In the jdk1.5 report warning, why? METHODM = Cls.getmethod ("test"); M.invoke (cls.newinstance (), NULL); M.invoke (Cls.newinstance ()); (test) Cls.newinstance ()). Test (); Return } else {FileInputStream FIS = newfileinputstream (args[0]); File F = new file (Args[1], NewFile (Args[0]). GetName ());//Do not check the directory for the last directory delimiter Fileoutputstreamfos = new FileOutputStream (f) ; Cypher (Fis,fos); Fis.close (); Fos.close (); The}}//class loader cannot load this non-public class/*exceptionin thread "main" Java.lang.IllegalAccessExcePtion:classmyclassloader can not access a member of class MyTest withmodifiers "" *//*classmytest{public void Test () { System.out.println ("hello,www.it315.org"); }}*/l writes a myservlet that can print out its own class loader name and the parent-child structure relationship chain of the current ClassLoader, and after normal publication, see that the print result is webappclassloader. L PUT the Myservlet.class file into the jar package, put it in the EXT directory, restart Tomcat, and found that the HttpServlet error was missing. L put Servlet.jar also put in the Ext directory, the problem solved, the result of printing is extclassloader. The class loaded by the parent class loader cannot refer to classes that can only be loaded by the Quilt class loader, such as: Ext directory is the EXT directory D:\javaprograms\Java\jdk1.6.0_01\jre\lib\ext in the JDK. The servlet placed in Tomcat is loaded by the ClassLoader Org.apache.catalina.loader.WebappClassLoader in Tomcat.
Java Basics like loaders