|
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.
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 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
CAUTION
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
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:
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 NamespacesEvery 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
Writing Your Own Class LoaderTo 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
Your implementation of this method must do the following:
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 programFor 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
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.java1. 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.java1. 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
java.lang.ClassLoader 1.0
java.lang.Thread 1.0
|
|