load/find class 与 forname 在static代码块加载的不同 (三)双亲委派
loadClass的双亲委派我们已经很熟了,再来看看forName的双亲委派
设计代码结构:
MyMain
lc5
TestForName URLClassLoader(MySub)
JustForName
MySub
lc5
JustForName
MyMain:
public class TestForName { public static void main(String []f) throws Exception { String dir = "file:/Users/sunyuming/Documents/tool/jars//MySub-1.0.0-jar-with-dependencies.jar"; URL url = null; try { url = new URL(dir); } catch (MalformedURLException e) { e.printStackTrace(); } URL[] urls = {url}; URLClassLoader myUrlClassLoader = new URLClassLoader(urls); Class.forName("lc5.JustForName", true, myUrlClassLoader); } } public class JustForName { static { System.out.println("JustForNameFather"); } }
MySub:
public class JustForName { static { System.out.println("JustForNameSon"); } }
输出:
JustForNameFather
结论:与loadClass一样,遵循双亲委派,无法用于绕开双亲委派