Java-class loaders and namespaces in Java

Source: Internet
Author: User

Functions and categories of class loaders

As the name suggests, the class loader is used to load classes into JVM. The JVM Specification defines two types of class loaders: start class loader (bootstrap) and user-defined loader (user-defined class loader ).

Bootstrap is a class loader that comes with JVM and is used to load core class libraries, such as Java. Lang. For example, java. Lang. object is loaded by bootstrap.

Java provides the abstract class classloader. All user-defined class loaders instantiate the class of the class loader. System class loader is an extraordinary user-defined class loader provided by the real-time JVM. It is loaded by default when programmers do not specify the loader. The system class loader can be obtained through the classloader. getsystemclassloader () method.

Example 1: Test the classloader of the JVM

/*LoaderSample1.java*/public class LoaderSample1 {    public static void main(String[] args) {        Class c;        ClassLoader cl;        cl = ClassLoader.getSystemClassLoader();        System.out.println(cl);        while (cl != null) {            cl = cl.getParent();            System.out.println(cl);        }        try {            c = Class.forName("java.lang.Object");            cl = c.getClassLoader();            System.out.println("java.lang.Object's loader is "   cl);            c = Class.forName("LoaderSample1");            cl = c.getClassLoader();            System.out.println("LoaderSample1's loader is "   cl);        } catch (Exception e) {            e.printStackTrace();        }    }}

Running results on my machine (Sun Java 1.5)

C: \ Java> JAVA loadersample1
Sun. Misc. launcher $ appclassloader @ 82ba41
Sun. Misc. launcher $ extclassloader @ 923e30
Java. Lang. Object's loader is null
Loadersample1's loader is Sun. Misc. launcher $ appclassloader @ 82ba41

The first line indicates that the system class loader is instantiated from the sun. Misc. launcher $ appclassloader class.

The second line indicates that the parent of the system class loader is instantiated from the sun. Misc. launcher $ extclassloader class.

The third line indicates that the parent of the system class loader is Bootstrap.

The fourth line indicates that the core class java. Lang. object is loaded by bootstrap.

The fifth line indicates that the user class loadersample1 is loaded by the system class loader.

Parent Delegation Model

Beginning with version 1.2, Java introduced the parent-parent Delegation Model to better ensure the security of the Java platform. In this model, when a loader is requested to load a class, it first delegates its own parent for loading. If the parent can be loaded, it returns the class object corresponding to the class, if the parent cannot be loaded, it is loaded by the parent requestor.

As shown in 1, the parent of loader2 is loader1, and the parent of loader1 is system class loader. Assume that loader2 is required to load the class myclass. In the parent Delegation Model, loader2 first requests loader1 for loading, and loader1 requests the system class loader for loading myclass. If the system loader can be loaded successfully, the reference of the Class Object corresponding to myclass is returned to loader1, and loader1 returns the reference to loader2, so that the class myclass is successfully loaded into the virtual machine. If the system class loader cannot load myclass, loader1 will try to load myclass. If loader1 cannot load successfully, loader2 will try to load. If neither the parent nor loader2 can be loaded, the loading fails.

If one of the class loaders can be loaded successfully, the actual class loaders are called the definition class loaders, and all the loaders (including the definition class loaders) that can successfully return class objects) it is called an initial class loader. 1. Assume that loader1 actually loads myclass, loader1 is the definition class loader of myclass, and loader2 and loader1 are the initial class loaders of myclass.

Figure 1 parent Delegation Model

It should be noted that class loader is an object, and its parent-child relationship does not have any relationship with the parent-child relationship of the class. A parent-child loader may be instantiated from the same class or not, or even the parent loader may be instantiated from the subclass, and the Child loader may be instantiated from the parent class. Assuming that myclassloader continues from parentclassloader, we can have the following parent-child Loader:

Classloader loader1 = new myclassloader (); // The parameter loader1 is parentclassloader loader2 = new parentclassloader (loader1 );

So why is the parent Delegation Model safer? In this model, the user-defined class loaders cannot load reliable classes that should be loaded by the parent loader, this prevents unreliable or even malicious code from replacing the reliable code loaded by the parent loader. In fact, the compiler of the class loader can choose not to delegate the request to the parent, but as mentioned above, it will bring security issues.

Namespace and its Functions

Each class loader has its own namespace, which is composed of all classes that use this loader as the initial class loader. The two classes in different namespaces are invisible, but you can still access the classes in another namespace as long as you get the reference of the Class Object corresponding to the class.

Example 2 demonstrates how a namespace class uses another namespace class. In this example, loadersample2 is loaded by the system class loader and loadersample3 is loaded by the custom loader. The two classes are not in the same namespace, however, loadersample2 obtains the reference of the Class Object corresponding to loadersample3, so it can access public members (such as age) in loadersampl3 ).

Example 2 Access to classes in different namespaces

/*LoaderSample2.java*/import java.net.*;import java.lang.reflect.*;public class LoaderSample2 {    public static void main(String[] args) {try {String path = System.getProperty("user.dir");URL[] us = {new URL("file://" path "/sub/")};ClassLoader loader = new URLClassLoader(us);Class c = loader.loadClass("LoaderSample3");Object o = c.newInstance();Field f = c.getField("age");int age = f.getInt(o);System.out.println("age is " age);} catch (Exception e) {e.printStackTrace();}}}

/*sub/Loadersample3.java*/public class LoaderSample3 {    static {        System.out.println("LoaderSample3 loaded");    }    public int age = 30;}

Compile:

Javac loadersample2.java; javac sub/loadersample3.java

Run: Java loadersample2

LoaderSample3 loadedage is 30                        

From the running results, we can see that in class loadersample2, you can create an object in class loadersample3 of another namespace and access its public member age.

Runtime package)

A runtime package consists of classes loaded by the same class loader and determines whether the two classes belong to the same runtime package. It depends not only on whether their package names are the same, check whether the class loaders are the same. Only classes belonging to the same runtime package can access classes and members visible to each other. This restriction avoids the situation where the user's code impersonates the class of the core class library and accesses the visible member of the core class library package. Assume that you have defined a Java class. lang. yes, it is loaded with a user-defined class loader, Because Java. lang. yes and core class library Java. lang. * loaded by different loaders, which belong to different runtime packages, so Java. lang. yes, you cannot access the core class library Java. visible member of the class package in Lang.

Summary

After a brief discussion of the Class Loader, parent Delegation Model, namespace, and runtime package, I believe everyone has a certain understanding of their functions. The namespace does not completely prohibit access to classes in different spaces. The parent-parent delegated model enhances Java security, and the runtime package adds protection for visible package members.

From: http://www2.oklinux.cn/html/developer/java/base/20080120/45998.html

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.