publicabstractclassClassLoader{ privatefinal ClassLoader parent; protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException{ synchronized (getClassLoadingLock(name)) { // First, check if the class has already been loaded Class<?> c = findLoadedClass(name); if (c == null) { // 当前类没有load 到 long t0 = System.nanoTime(); try { if (parent != null) { c = parent.loadClass(name, false); // 如果当前没有load 到 则从父加载器load 递归过程 } else { c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { }
if (c == null) { long t1 = System.nanoTime(); c = findClass(name); // 如果所有的加载器都没有缓存到,则自己加载 递归 找到直接返回 // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { resolveClass(c); } return c; } } }
publicclassT012_ClassReloading2{ privatestaticclassMyLoaderextendsClassLoader{ @Override public Class<?> loadClass(String name) throws ClassNotFoundException { File f = new File("C:/JVM/" + name.replace(".", "/").concat(".class")); if(!f.exists()) returnsuper.loadClass(name); try { InputStream is = new FileInputStream(f); byte[] b = newbyte[is.available()]; is.read(b); return defineClass(name, b, 0, b.length); } catch (IOException e) { e.printStackTrace(); } returnsuper.loadClass(name); } }
publicstaticvoidmain(String[] args)throws Exception { MyLoader m = new MyLoader(); Class clazz = m.loadClass("com.chase.jvm.Hello"); m = new MyLoader(); Class clazzNew = m.loadClass("com.chase.jvm.Hello"); System.out.println(clazz == clazzNew); } }