继承ClassLoader并且重写findClass方法就可以自定义一个类加载器,具体什么是类加载器以及类加载器的加载过程与顺序下次再说,下面给出一个小demo
首先定义一个类,比如MyTest,并且将其编译成class文件,然后放到一个指定的文件夹下面,其中文件夹的最后几层就是它的包名,这里我将这个编译好的类放到 : /Users/allen/Desktop/cn/lijie/MyTest.class
package cn.lijie;
public class MyTest {
public void show() {
System.out.println("show test!");
}
}
自定义的类加载器:
public class MyClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) {
String myPath = "file:///Users/allen/Desktop/" + name.replace(".","/") + ".class";
System.out.println(myPath);
byte[] cLassBytes = null;
Path path = null;
try {
path = Paths.get(new URI(myPath));
cLassBytes = Files.readAllBytes(path);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);
return clazz;
}
}
测试的主函数:
public class MainClass {
public static void main(String[] args) throws ClassNotFoundException {
MyClassLoader loader = new MyClassLoader();
Class<?> aClass = loader.findClass("cn.lijie.MyTest");
try {
Object obj = aClass.newInstance();
Method method = aClass.getMethod("show");
method.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行主函数,调用外部class的show方法: