classloader getresource jar包资源冲突情况,父亲为大,兄弟之间,谁先加载谁牛逼(二)
getResources一起加载,URL.openStream
public class LcProperty { public static void main(String [] x) throws IOException { } public static String read(String conf) throws IOException { .. } public static String reads(String conf) throws IOException { System.out.println(LcProperty.class.getClassLoader().getResources(conf)); Enumeration<URL> urlEnumeration = LcProperty.class.getClassLoader().getResources(conf); while(urlEnumeration.hasMoreElements()){ URL url = urlEnumeration.nextElement(); System.out.println(url); InputStream inputStream = url.openStream(); byte [] bytes = new byte[20]; inputStream.read(bytes); String out = new String(bytes); System.out.println(out); } return urlEnumeration.toString(); } }
/* 故意让brother在前面,以此证明即使在sub.jar中调用getresource也不会优先查 sub中的资源或类,而会去查被优先加载的brother.jar 这个加载顺序取决于操作系统 */ // //// Method method3 = c1.getMethod("reads", String.class); System.out.println("start reads father.conf"); method3.invoke(null, "father.conf"); System.out.println("start reads self.conf"); method3.invoke(null, "self.conf"); System.out.println("start reads brother.conf"); method3.invoke(null, "brother.conf"); Method method4 = c2.getMethod("reads", String.class); System.out.println("start reads father.conf"); method4.invoke(null, "father.conf"); System.out.println("start reads self.conf"); method4.invoke(null, "self.conf"); System.out.println("start reads brother.conf"); method4.invoke(null, "brother.conf");
start reads father.conf sun.misc.CompoundEnumeration@34c45dca file:/Users/joyce/work/MyTest/MyMain/target/classes/father.conf father jar:file:/Users/sunyuming/Documents/tool/jars//MySub-1.0.0-jar-with-dependencies.jar!/father.conf self jar:file:/Users/sunyuming/Documents/tool/jars//MySubBrother-1.0.0-jar-with-dependencies.jar!/father.conf brother start reads self.conf sun.misc.CompoundEnumeration@27bc2616 jar:file:/Users/sunyuming/Documents/tool/jars//MySub-1.0.0-jar-with-dependencies.jar!/self.conf self jar:file:/Users/sunyuming/Documents/tool/jars//MySubBrother-1.0.0-jar-with-dependencies.jar!/self.conf brother start reads brother.conf sun.misc.CompoundEnumeration@1ddc4ec2 jar:file:/Users/sunyuming/Documents/tool/jars//MySubBrother-1.0.0-jar-with-dependencies.jar!/brother.conf brother
JDBC SPI 类加载机制 JDBC就使用了这种方式遍历当前线程类加载器中所有resources/META-INF/services/下的java.sql.Driver文件