最近作了一個根據同一模塊的不一樣jar版本作同時測試的工具,感受挺有意思,特此記錄。html
把類加載階段中的「經過一個類的全限定名(博主注:絕對路徑)來獲取描述此類的二進制字節流」這個動做放在Java虛擬機外部去實現,以便讓應用程序本身決定如何去獲取所須要的類。實現這個動做的代碼模塊成爲」類加載器「。摘自周志明的《深刻理解Java虛擬機》java
總之,ClassLoader很重要,Java世界須要它。eclipse
本人在本地生成了test1.jar和test2.jar兩個jar包。這兩個jar都有類com.array7.jvm.classloader.Target
,此Demo要實現的是同時將這兩個jar包的同名類加載到JVM而且各自執行。
** test1.jar Target.java **jvm
package com.array7.jvm.classloader; public class Target { public static void main(String[] args) { System.out.print("test1"); } }
** test2.jar Target.java **工具
package com.array7.jvm.classloader; public class Target { public static void main(String[] args) { System.out.print("test2"); } }
** TestDriver**測試
public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { ClassLoader loader1 = new URLClassLoader(new URL[]{new URL("file:/home/liushijie/workspace/test/out/artifacts/test1/test1.jar")}, TestDriver.class.getClassLoader()); ClassLoader loader2 = new URLClassLoader(new URL[]{new URL("file:/home/liushijie/workspace/test/out/artifacts/test2/test2.jar")}, TestDriver.class.getClassLoader()); String className = "com.array7.jvm.classloader.Target"; // loader1 System.out.print("test1.jar \t"); Class clazz1 = Class.forName(className, true, loader1); clazz1.getMethod("main", String[].class).invoke(null, (Object) null); System.out.println(); // loader2 System.out.print("test2.jar \t"); Class clazz2 = Class.forName(className, true, loader2); clazz2.getMethod("main", String[].class).invoke(null, (Object) null); System.out.println(); System.out.println("實例化後是否相等:" + clazz1.equals(clazz2)); }
test1.jar test1 test2.jar test2 實例化後是否相等:false