Java class loading mechanism (c)

Class loader

Virtual machine design team in the class loading phase: to get through the fully qualified name of a class description of such a binary byte stream, this action to the outside Java virtual machine to achieve, to allow the application to decide how to get the required the type. This action is achieved code module called a "class loader."

Class loader can be said to be an innovation of the Java language, it is one of the important reasons for the popular Java language, which was originally to meet the needs of Java Applet and developed. Although Java Applet technology is basically already dead, but the class loader was in the class hierarchy division, OSGI, hot deployment, code encryption and other fields shine, become an important cornerstone of the Java technology system, really lost Sang Yu to close the east corner!

Class and class loader

While only the class loader used to load the implementation class action, but he played a role in a Java program is far from limited to class loading stage. For any category, you need to load it established by the class loader and the class itself with its uniqueness in the Java virtual machine, each class loader has a separate class namespace. This sentence can express some of the more popular: comparison of two classes are equal, and only under the premise of these two classes are loaded by the same class loader makes sense, otherwise, even if it comes from a class with two classes file, is loaded with a virtual machine, which is to load their different class loaders, two classes that will surely not equal.

Referred to herein equal, equals comprising representatives of the class of Class objects, inInstance method, IsAssignableFrom method returns a result, the keywords that also includes the use instanceof relationship determining where the object belongs and the like. If the notice does not affect the class loader, and in some cases it might result in confusing nature.

public class ClassLoaderTest {
   public static void main(String[] args) throws Exception {
      ClassLoader myLoader = new ClassLoader() {
         @Override
         public Class<?> loadClass(String name) throws ClassNotFoundException {
            try{
               String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
               InputStream is = getClass().getResourceAsStream(fileName);
               if(is == null){
                  return super.loadClass(name);
               }
               byte[] b = new byte[is.available()];
               is.read(b);
               return defineClass(name,b,0,b.length);
            }catch (Exception e){
               throw new ClassNotFoundException(name);
            }
         }
      };
      Object obj = myLoader.loadClass("com.bzy.sf.ClassLoaderTest").newInstance();
      System.out.println(obj.getClass());
      System.out.println(obj instanceof com.bzy.sf.DeadLoopClass);
   }
}

The above code constructs a simple class loader can load class files with their same path. We use this class loader to load a class, and instantiate an object of this class, was found from the results, DeadLoopClass this object is not an instance of the virtual machine exists two classLoaderTest class, is loaded by a class system applications loaded, and the other is our custom class loader loaded, although all from the same class file, it is still two separate classes, do type checking object belongs result is naturally false.

Parents delegate mode

From the java virtual machine perspective, there are only two different class loaders: one is to start class loader (Bootstrap classLoader), the class loader uses the C ++ language, is part of the virtual machine itself; the other is all other class loader, the class loader by the Java language, independent of external virtual machine, and all derived from the abstract class java.lang.ClassLoader.

From the Java developer perspective, the class loader can also be divided more detail some of the vast majority of Java programmers will use the following three class loader provided by the system.

Boot class loader: This class is responsible for loading will be stored in java_home / lib directory, or by -Xbootclasspath parameter specified path, and a virtual machine identification (identified only by name, such as rt.jar, name the library does not meet even the lib directory will not be loaded) libraries loaded into the virtual machine's memory. Start class loader can not be directly referenced Java program, users write custom class loader, if you need to load the delegates to the bootstrap class loader that directly only to null.

Extension class loader (Extension ClassLoader): This loader is implemented by sun.misc.Lanuncher, he was responsible for loading java_home lib \ ext directory or are specified java.ext.dirs system variables path \ All libraries , developers can directly use the extension class loader.

Application class loader: This class is implemented by sun.misc.Laucher $ App-ClassLoader. Since this class is loaded in classLoader getSystemClassLoader () Returns the value of the method, it is generally called the system class loader. It is responsible for loading the user class path specified class library, developers can directly use this class loader, if the application is not too own custom class loader, in general, this program is the default class loader.

Our applications are co-ordinated by the three class loader loads and, if necessary, can be added to a custom class loader. The relationship between these class loader is generally: this hierarchical relationship between the pictures show class loader, called the parent class loader delegation model. Parents deal with top-level delegation model boot class loader, the rest of the class loader should have its own parent class loader. Here parent-child relationship between the class loader is generally not achieved to inheritance relationship, but use a combination of the code multiplexing relationship with the parent loader.

Class parents delegation model is not a mandatory constraint model, but the designers recommend to the proposition Java class loader developer's implementation.

Parent delegation model is working process: If a class loader loads the class received a request, it first does not own to try to load this class, but to delegate this request to the parent class loader to complete each level of the class loader is true, so all requests will eventually be transferred load to the top of the boot class loader, loader feedback only when the parent they can not complete the loading request (its search did not find the desired category), the child loader will try to load your own.

Use parent delegation model to organize the relationship between the class loader, there is an obvious advantage is that Java class with its class loader has the priority level of a relationship of having together. For example class java.lang.Object, store it in rt.jar, no matter which class loader to load this class are ultimately assigned to the model in the top of the boot class loader to load, once the Object class in each program the type loader environments are the same class. On the contrary, if no parent delegation model, by each class loader to load their own words, if you have written a class called java.lang.Object and in the classpath of the program, that there will be a number of different systems the Object class, Java type system, the most basic of behavior will not be able to ensure that the application will be chaos.
Delegation model is important for parents to ensure the stable operation of the Java programs, but its implementation is very simple, parents realized delegated codes are concentrated in the loadClass method Java.lang.ClassLoader in the following figure, clear and understandable logic: first check whether it is loaded too, if not loaded loadclass method is called the parent loader, loader if a parent is empty default boot loader class loader as a parent, if the parent fails to load, an exception is thrown, then call their method findclass loading.

 

Guess you like

Origin blog.csdn.net/qq_37113604/article/details/90476605