Задача: Загрузчик классов
Исходник: Загрузчик апплетов, язык: java [code #195, hits: 7408]
автор: - [добавлен: 02.05.2007]
  1. import java.applet.Applet;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.net.MalformedURLException;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7. import java.util.Hashtable;
  8.  
  9. import javax.swing.JFrame;
  10.  
  11. public class MainClass {
  12.  
  13. public static void main(String args[]) {
  14. String name = "http://urlWithClassName";
  15. try {
  16. if (!name.endsWith(".class")) {
  17. System.err.println("That doesn't look like a byte code file!");
  18. return;
  19. }
  20. URL u = new URL(name);
  21.  
  22. // parse out the name of the class from the URL
  23. String s = u.getFile();
  24. String classname = s.substring(s.lastIndexOf('/'), s.lastIndexOf(".class"));
  25. Class AppletClass = ucl.loadClass(classname, true);
  26. Applet apl = (Applet) AppletClass.newInstance();
  27. JFrame f = new JFrame();
  28. f.setSize(200, 200);
  29. f.add("Center", apl);
  30. apl.init();
  31. apl.start();
  32. f.setVisible(true);
  33. } catch (Exception e) {
  34. System.err.println(e);
  35. }
  36. }
  37. }
  38.  
  39. class URLClassLoader extends ClassLoader {
  40. Hashtable cache = new Hashtable();
  41. URL url;
  42.  
  43. public URLClassLoader(URL u) {
  44. this.url = u;
  45. }
  46.  
  47. public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
  48. Class cls = (Class) cache.get(name);
  49. if (cls == null) {
  50. try {
  51. cls = findSystemClass(name);
  52. } catch (ClassNotFoundException e) {
  53. }
  54. }
  55. if (cls == null) {
  56. byte classData[] = loadClassData(name);
  57. cls = defineClass(classData, 0, classData.length);
  58. cache.put(name, cls);
  59. }
  60. if (resolve) {
  61. resolveClass(cls);
  62. }
  63. return cls;
  64. }
  65. private byte[] loadClassData(String name) throws ClassNotFoundException {
  66. byte[] buffer;
  67. InputStream theClassInputStream = null;
  68. int bufferLength = 128;
  69. try {
  70. URL classURL = new URL(url, name + ".class");
  71. URLConnection uc = classURL.openConnection();
  72. uc.setAllowUserInteraction(false);
  73.  
  74. try {
  75. theClassInputStream = uc.getInputStream();
  76. } catch (NullPointerException e) {
  77. System.err.println(e);
  78. throw new ClassNotFoundException(name + " input stream problem");
  79. }
  80. int contentLength = uc.getContentLength();
  81.  
  82. // A lot of web servers don't send content-lengths
  83. // for .class files
  84. if (contentLength == -1) {
  85. buffer = new byte[bufferLength * 16];
  86. } else {
  87. buffer = new byte[contentLength];
  88. }
  89.  
  90. int bytesRead = 0;
  91. int offset = 0;
  92.  
  93. while (bytesRead >= 0) {
  94. bytesRead = theClassInputStream.read(buffer, offset, bufferLength);
  95. if (bytesRead == -1)
  96. break;
  97. offset += bytesRead;
  98. if (contentLength == -1 && offset == buffer.length) { // grow the array
  99. byte temp[] = new byte[offset * 2];
  100. System.arraycopy(buffer, 0, temp, 0, offset);
  101. buffer = temp;
  102. } else if (offset > buffer.length) {
  103. throw new ClassNotFoundException(name + " error reading data into the array");
  104. }
  105. }
  106.  
  107. if (offset < buffer.length) { // shrink the array
  108. byte temp[] = new byte[offset];
  109. System.arraycopy(buffer, 0, temp, 0, offset);
  110. buffer = temp;
  111. }
  112.  
  113. // Make sure all the bytes were received
  114. if (contentLength != -1 && offset != contentLength) {
  115. throw new ClassNotFoundException("Only " + offset + " bytes received for " + name
  116. + "\n Expected " + contentLength + " bytes");
  117. }
  118. } catch (Exception e) {
  119. throw new ClassNotFoundException(name + " " + e);
  120. } finally {
  121. try {
  122. if (theClassInputStream != null)
  123. theClassInputStream.close();
  124. } catch (IOException e) {
  125. }
  126. }
  127. return buffer;
  128. }
  129. }
По указываемому адресу загружается байт-код апплета.
Создается простенькое окошко для демострации его выполнения.
Загруженный в jvm новый исполяемый код апплета далее в нем запускается
Тестировалось на: java 1.5.0_04

+добавить реализацию