Class Loaders


A Java compiler converts source into the machine language of a hypothetical machine, called the virtual machine. The virtual machine code is stored in a class file with a .class extension. Each class file contains the definition and implementation code for one class or interface. These class files must be interpreted by a program that can translate the instruction set of the virtual machine into the machine language of the target machine.

Note that the virtual machine loads only those class files that are needed for the execution of a program. For example, suppose program execution starts with MyProgram.class. Here are the steps that the virtual machine carries out.

  1. The virtual machine has a mechanism for loading class files, for example, by reading the files from disk or by requesting them from the Web; it uses this mechanism to load the contents of the MyProgram class file.

  2. If the MyProgram class has instance variables or superclasses of another class type, these class files are loaded as well. (The process of loading all the classes that a given class depends on is called resolving the class.)

  3. The virtual machine then executes the main method in MyProgram (which is static, so no instance of a class needs to be created).

  4. If the main method or a method that main calls requires additional classes, these are loaded next.

The class loading mechanism doesn't just use a single class loader, however. Every Java program has at least three class loaders:

  • The bootstrap class loader

  • The extension class loader

  • The system class loader (also sometimes called the application class loader)

The bootstrap class loader loads the system classes (typically, from the JAR file rt.jar). It is an integral part of the virtual machine and is usually implemented in C. There is no ClassLoader object corresponding to the bootstrap class loader. For example,

 String.class.getClassLoader() 

returns null.

The extension class loader loads "standard extensions" from the jre/lib/ext directory. You can drop JAR files into that directory, and the extension class loader will find the classes in them, even without any class path. (Some people recommend this mechanism to avoid the "class path from hell," but see the cautionary notes below.)

The system class loader loads the application classes. It locates classes in the directories and JAR/ZIP files on the class path, as set by the CLASSPATH environment variable or the -classpath command-line option.

In Sun's Java implementation, the extension and system class loaders are implemented in Java. Both are instances of the URLClassLoader class.

CAUTION

You can run into grief if you drop a JAR file into the jre/lib/ext directory and one of its classes needs to load a class that is not a system or extension class. The extension class loader does not use the class path. Keep that in mind before you use the extension directory as a way to manage your class file hassles.


CAUTION

There is a second pitfall with dropping JAR files into the jre/lib/ext directory. Sometimes, programmers forget about the files they placed there months ago. Then they scratch their heads when the class loader seems to ignore the class path, when it is actually loading long-forgotten classes from the extension directory.


Class loaders have a parent/child relationship. Every class loader except for the bootstrap class loader has a parent class loader. A class loader is supposed to give its parent a chance to load any given class and only load it if the parent has failed. For example, when the system class loader is asked to load a system class (say, java.util.ArrayList), then it first asks the extension class loader. That class loader first asks the bootstrap class loader. The bootstrap class loader finds and loads the class in rt.jar, and neither of the other class loaders searches any further.

NOTE

When implementing a class loader, you should always delegate class loading to the parent first. Otherwise, there is a potential security risk: The custom class loader can accidentally load a version of a system class that bypasses important security checks.


Applets, servlets, and RMI stubs are loaded with custom class loaders. You can even write your own class loader for specialized purposes. That lets you carry out specialized security checks before you pass the bytecodes to the virtual machine. For example, you can write a class loader that can refuse to load a class that has not been marked as "paid for." The next section shows you how.

Most of the time, you don't have to worry about class loaders. Most classes are loaded because they are required by other classes, and that process is transparent to you.

If you load a class programmatically, by calling Class.forName, then the new class is loaded with the same class loader that loaded the code that calls Class.forName. Generally, this is the right behavior. However, it fails in the following circumstances:

  1. You implement a library class with a method that calls Class.forName.

  2. Your method is called from an application class that was loaded with a different class loader than the library class.

  3. The loaded class is not visible from the class loader that loaded the library class.

In that case, the library class needs to work harder and retrieve the application's class loader:

 Thread t = Thread.currentThread(); ClassLoader loader = t.getContextClassLoader(); Class cl = loader.loadClass(className); 

Using Class Loaders as Namespaces

Every Java programmer knows that package names are used to eliminate name conflicts. There are two classes called Date in the standard library, but of course their real names are java.util.Date and java.sql.Date. The simple name is only a programmer convenience and requires the inclusion of appropriate import statements. In a running program, all class names contain their package name.

It may surprise you, however, that you can have two classes in the same virtual machine that have the same class and package name. A class is determined by its full name and the class loader. This technique is useful for loading code from multiple sources. For example, a browser uses separate instances of the applet class loader class for each web page. This allows the virtual machine to separate classes from different web pages, no matter what they are named.

NOTE

This technique has other uses as well, such as "hot deployment" of servlets and Enterprise JavaBeans. See http://java.sun.com/developer/TechTips/2000/tt1027.html for more information.


Writing Your Own Class Loader

To write your own class loader, you simply extend the ClassLoader class and override the method.

 findClass(String className) 

The loadClass method of the ClassLoader superclass takes care of the delegation to the parent and calls findClass only if the class hasn't already been loaded and if the parent class loader was unable to load the class.

NOTE

In earlier versions of the JDK, programmers had to override the loadClass method. That practice is no longer recommended.


Your implementation of this method must do the following:

  1. Load the bytecodes for the class from the local file system or from some other source.

  2. Call the defineClass method of the ClassLoader superclass to present the bytecodes to the virtual machine.

In the program of Example 9-1, we implement a class loader that loads encrypted class files. The program asks the user for the name of the first class to load (that is, the class containing main) and the decryption key. It then uses a special class loader to load the specified class and calls the main method. The class loader decrypts the specified class and all nonsystem classes that are referenced by it. Finally, the program calls the main method of the loaded class (see Figure 9-1).

Figure 9-1. The ClassLoaderTest program


For simplicity, we ignore 2,000 years of progress in the field of cryptography and use the venerable Caesar cipher for encrypting the class files.

NOTE

David Kahn's wonderful book The Codebreakers [Macmillan, NY, 1967, p. 84] refers to Suetonius as a historical source for the Caesar cipher. Caesar shifted the 24 letters of the Roman alphabet by 3 letters. When this chapter was first written, the U.S. government restricted the export of strong encryption methods. Therefore, we used Caesar's method for our example since it was clearly legal for export.


Our version of the Caesar cipher has as a key a number between 1 and 255. To decrypt, simply add that key to every byte and reduce modulo 256. The Caesar.java program of Example 9-2 carries out the encryption.

So that we do not confuse the regular class loader, we use a different extension, .caesar, for the encrypted class files.

To decrypt, the class loader simply subtracts the key from every byte. In the companion code for this book, you will find four class files, encrypted with a key value of 3the traditional choice. To run the encrypted program, you need the custom class loader defined in our ClassLoaderTest program.

Encrypting class files has a number of practical uses (provided, of course, that you use a cipher stronger than the Caesar cipher). Without the decryption key, the class files are useless. They can neither be executed by a standard virtual machine nor readily disassembled.

This means that you can use a custom class loader to authenticate the user of the class or to ensure that a program has been paid for before it will be allowed to run. Of course, encryption is only one application of a custom class loader. You can use other types of class loaders to solve other problems, for example, storing class files in a database.

Example 9-1. ClassLoaderTest.java
   1. import java.util.*;   2. import java.io.*;   3. import java.lang.reflect.*;   4. import java.awt.*;   5. import java.awt.event.*;   6. import javax.swing.*;   7.   8. /**   9.    This program demonstrates a custom class loader that decrypts  10.    class files.  11. */  12. public class ClassLoaderTest  13. {  14.    public static void main(String[] args)  15.    {  16.       JFrame frame = new ClassLoaderFrame();  17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  18.       frame.setVisible(true);  19.    }  20. }  21.  22. /**  23.    This frame contains two text fields for the name of the class  24.    to load and the decryption key.  25. */  26. class ClassLoaderFrame extends JFrame  27. {  28.    public ClassLoaderFrame()  29.    {  30.       setTitle("ClassLoaderTest");  31.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);  32.       setLayout(new GridBagLayout());  33.       add(new JLabel("Class"), new GBC(0, 0).setAnchor(GBC.EAST));  34.       add(nameField, new GBC(1, 0).setWeight(100, 0).setAnchor(GBC.WEST));  35.       add(new JLabel("Key"), new GBC(0, 1).setAnchor(GBC.EAST));  36.       add(keyField, new GBC(1, 1).setWeight(100, 0).setAnchor(GBC.WEST));  37.       JButton loadButton = new JButton("Load");  38.       add(loadButton, new GBC(0, 2, 2, 1));  39.       loadButton.addActionListener(new  40.          ActionListener()  41.          {  42.             public void actionPerformed(ActionEvent event)  43.             {  44.                runClass(nameField.getText(), keyField.getText());  45.             }  46.          });  47.       pack();  48.    }  49.  50.    /**  51.       Runs the main method of a given class.  52.       @param name the class name  53.       @param key the decryption key for the class files  54.    */  55.    public void runClass(String name, String key)  56.    {  57.       try  58.       {  59.          ClassLoader loader = new CryptoClassLoader(Integer.parseInt(key));  60.          Class c = loader.loadClass(name);  61.          String[] args = new String[] {};  62.  63.          Method m = c.getMethod("main", args.getClass());  64.          m.invoke(null, (Object) args);  65.       }  66.       catch (Throwable e)  67.       {  68.          JOptionPane.showMessageDialog(this, e);  69.       }  70.    }  71.  72.    private JTextField keyField = new JTextField("3", 4);  73.    private JTextField nameField = new JTextField(30);  74.    private static final int DEFAULT_WIDTH = 300;  75.    private static final int DEFAULT_HEIGHT = 200;  76. }  77.  78. /**  79.    This class loader loads encrypted class files.  80. */  81. class CryptoClassLoader extends ClassLoader  82. {  83.    /**  84.       Constructs a crypto class loader.  85.       @param k the decryption key  86.    */  87.    public CryptoClassLoader(int k)  88.    {  89.       key = k;  90.    }  91.  92.    protected Class findClass(String name)  93.       throws ClassNotFoundException  94.    {  95.       byte[] classBytes = null;  96.       try  97.       {  98.          classBytes = loadClassBytes(name);  99.       } 100.       catch (IOException e) 101.       { 102.          throw new ClassNotFoundException(name); 103.       } 104. 105.       Class cl = defineClass(name, classBytes, 0, classBytes.length); 106.       if (cl == null) 107.          throw new ClassNotFoundException(name); 108.       return cl; 109.    } 110. 111.    /** 112.       Loads and decrypt the class file bytes. 113.       @param name the class name 114.       @return an array with the class file bytes 115.    */ 116.    private byte[] loadClassBytes(String name) 117.       throws IOException 118.    { 119.       String cname = name.replace('.', '/') + ".caesar"; 120.       FileInputStream in = null; 121.       in = new FileInputStream(cname); 122.       try 123.       { 124.          ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 125.          int ch; 126.          while ((ch = in.read()) != -1) 127.          { 128.             byte b = (byte) (ch - key); 129.             buffer.write(b); 130.          } 131.          in.close(); 132.          return buffer.toByteArray(); 133.       } 134.       finally 135.       { 136.          in.close(); 137.       } 138.    } 139. 140.    private int key; 141. } 

Example 9-2. Caesar.java
  1. import java.io.*;  2.  3. /**  4.    Encrypts a file using the Caesar cipher.  5. */  6. public class Caesar  7. {  8.    public static void main(String[] args)  9.    { 10.       if (args.length != 3) 11.       { 12.          System.out.println("USAGE: java Caesar in out key"); 13.          return; 14.       } 15. 16.       try 17.       { 18.          FileInputStream in = new FileInputStream(args[0]); 19.          FileOutputStream out = new FileOutputStream(args[1]); 20.          int key = Integer.parseInt(args[2]); 21.          int ch; 22.          while ((ch = in.read()) != -1) 23.          { 24.             byte c = (byte)(ch + key); 25.             out.write(c); 26.          } 27.          in.close(); 28.          out.close(); 29.       } 30.       catch (IOException exception) 31.       { 32.          exception.printStackTrace(); 33.       } 34.    } 35. } 


 java.lang.Class 1.0 

  • ClassLoader getClassLoader()

    gets the class loader that loaded this class.


 java.lang.ClassLoader 1.0 

  • ClassLoader getParent() 1.2

    returns the parent class loader, or null if the parent class loader is the bootstrap class loader.

  • static ClassLoader getSystemClassLoader() 1.2

    gets the system class loader, that is, the class loader that was used to load the first application class.

  • protected Class findClass(String name) 1.2

    should be overridden by a class loader to find the bytecodes for a class and present them to the virtual machine by calling the defineClass method.

    Parameters:

    name

    The name of the class; use . as package name separator, and don't use a .class suffix


  • Class defineClass(String name, byte[] data, int offset, int length)

    adds a new class to the virtual machine.

    Parameters:

    name

    The name of the class; use . as package name separator, and don't use a .class suffix

     

    data

    An array holding the bytecodes of the class

     

    offset

    The start of the bytecodes in the array

     

    length

    The length of the bytecodes in the array



 java.lang.Thread 1.0 

  • ClassLoader getContextClassLoader() 1.2

    gets the class loader that the creator of this thread has designated as the most reasonable class loader to use when executing this thread.

  • void setContextClassLoader(ClassLoader loader) 1.2

    sets a class loader for code in this thread to retrieve for loading classes. If no context class loader is set explicitly when a thread is started, the parent's context class loader is used.



    Core JavaT 2 Volume II - Advanced Features
    Building an On Demand Computing Environment with IBM: How to Optimize Your Current Infrastructure for Today and Tomorrow (MaxFacts Guidebook series)
    ISBN: 193164411X
    EAN: 2147483647
    Year: 2003
    Pages: 156
    Authors: Jim Hoskins

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net