日期:2014-05-20 浏览次数:20714 次
package code.loader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class ClassLoaderDemo {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
try {
// 测试路径
String classPath1 = "file:/E:/eclipse/workspace/OK/bin/code/mytest";
String classPath2 = "file:/E:/eclipse/workspace/OK/bin/code/mytest";
// 测试类
String className1 = "Tesst2";
String className2 = "Tesst2";
// 创建个URL
URL url1 = new URL(classPath1);
// 建立ClassLoader
ClassLoader loader1 = new URLClassLoader(new URL[] {url1});
System.out.println(className1);
// 载入类
Class c1 = loader1.loadClass(className1);
System.out.println(c1);
URL url2 = new URL(classPath2);
ClassLoader loader2 = new URLClassLoader(new URL[] {url2});
Class c2 = loader2.loadClass(className2);
System.out.println(c2);
System.out.println("是否相同?" + (c1 == c2));
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("路劲不对");
}
catch(MalformedURLException e) {
System.out.println("载入路径错误");
}
catch(ClassNotFoundException e) {
System.out.println("找不到指定的类");
}
}
}