/test/kilim/test/TaskTestClassLoader.java

http://github.com/kilim/kilim · Java · 74 lines · 58 code · 8 blank · 8 comment · 10 complexity · 67bcc269055d933f2f3f4cbb27701785 MD5 · raw file

  1. /* Copyright (c) 2006, Sriram Srinivasan
  2. *
  3. * You may distribute this software under the terms of the license
  4. * specified in the file "License"
  5. */
  6. package kilim.test;
  7. import java.io.File;
  8. import java.io.FileInputStream;
  9. import java.io.IOException;
  10. import java.net.URL;
  11. public class TaskTestClassLoader extends ClassLoader {
  12. static String wclassDir;
  13. static {
  14. URL baseURL = Thread.currentThread().getContextClassLoader().getResource("kilim/test/TaskTestClassLoader.class");
  15. String path = baseURL.getPath();
  16. wclassDir = path.substring(0, path.indexOf("/classes/")) + "/wclasses/";
  17. }
  18. public TaskTestClassLoader(ClassLoader aParent) {
  19. super(aParent);
  20. }
  21. @Override
  22. public Class<?> loadClass(String className, boolean resolve)
  23. throws ClassNotFoundException {
  24. Class<?> ret = findLoadedClass(className);
  25. if (ret == null && className.startsWith("kilim")) {
  26. File f = new File(wclassDir + className.replace('.', '/') + ".class");
  27. if (f.exists()) {
  28. try {
  29. byte[] bytes = getBytes(f);
  30. // if (resolve) {
  31. ret = defineClass(className, bytes, 0, bytes.length);
  32. // }
  33. } catch (IOException ioe) {
  34. System.err.println("Error loading class " + className + " from file " + f.getPath());
  35. ioe.printStackTrace();
  36. // Not supposed to happen
  37. System.exit(1);
  38. }
  39. }
  40. }
  41. if (ret == null) {
  42. return resolve ? findSystemClass(className)
  43. : getParent().loadClass(className);
  44. } else {
  45. return ret;
  46. }
  47. }
  48. private byte[] getBytes(File f) throws IOException {
  49. int size = (int)f.length();
  50. byte[] bytes = new byte[size];
  51. int remaining = size;
  52. int i = 0;
  53. FileInputStream fis = new FileInputStream(f);
  54. while (remaining > 0) {
  55. int n = fis.read(bytes, i, remaining);
  56. if (n == -1) break;
  57. remaining -= n;
  58. i += n;
  59. }
  60. return bytes;
  61. }
  62. public static void main(String[] args) throws Exception {
  63. Class<?> c = new TaskTestClassLoader(Thread.currentThread().getContextClassLoader()).loadClass(args[0], true);
  64. c.newInstance();
  65. }
  66. }