双亲委派机制

源码分析「Java.lang.ClassLoader」

1.parent

  1. // The parent class loader for delegation
  2. // Note: VM hardcoded the offset of this field, thus all new fields
  3. // must be added *after* it.
  4. private final ClassLoader parent;

2.loadClass

  1. public Class<?> loadClass(String name) throws ClassNotFoundException {
  2. return loadClass(name, false);
  3. }
  4. protected Class<?> loadClass(String name, boolean resolve)
  5. throws ClassNotFoundException
  6. {
  7. synchronized (getClassLoadingLock(name)) {
  8. // First, check if the class has already been loaded
  9. Class<?> c = findLoadedClass(name);
  10. if (c == null) {
  11. long t0 = System.nanoTime();
  12. try {
  13. if (parent != null) {
  14. c = parent.loadClass(name, false);
  15. } else {
  16. c = findBootstrapClassOrNull(name);
  17. }
  18. } catch (ClassNotFoundException e) {
  19. // ClassNotFoundException thrown if class not found
  20. // from the non-null parent class loader
  21. }
  22. if (c == null) {
  23. // If still not found, then invoke findClass in order
  24. // to find the class.
  25. long t1 = System.nanoTime();
  26. c = findClass(name);
  27. // this is the defining class loader; record the stats
  28. sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
  29. sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
  30. sun.misc.PerfCounter.getFindClasses().increment();
  31. }
  32. }
  33. if (resolve) {
  34. resolveClass(c);
  35. }
  36. return c;
  37. }
  38. }
  39. protected Class<?> findClass(String name) throws ClassNotFoundException {
  40. throw new ClassNotFoundException(name);
  41. }