自定义类加载器:
package ClassLoader;
import java.io.*;
/**
* 自定义类加载器
* @ Author :xuefeng
* @ Date :2019/2/27 4:50 PM
*/
public class MyClassLoader extends ClassLoader{
private String path;// 加载类的路径
private String name;// 加载累的名称
public MyClassLoader(String name,String path){
super();// 让系统类加载器成为该类的父加载器
this.name = name;
this.path = path;
}
public MyClassLoader(ClassLoader parent, String name,String path){
super(parent);// 显示指定父类加载器
this.name = name;
this.path = path;
}
/**
* 加载我们自定义的类,通过我们自定义的这个ClassLoader
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] data = readClasFileToByteArray(name);// 读取类文件转换成二进制字节数组
return this.defineClass(name,data,0,data.length);
}
/**
*获取.class文件的字节数组
* 例如:ClassLoader.demo1 -- > F:/ClassLoader/demo1.class
* @param name
* @return
*/
private byte[] readClasFileToByteArray(String name){
InputStream is = null;
byte[] returnData = null;
//把文件.转换成/
// name = name.replaceAll("\\.","/"); //win 下
name = name.replaceAll("\\.", File.separator); //linux 下
//构造路径
String filePath = this.path + name + ".class";
File file = new File(filePath);
//通过文件的输入流把文件读取出来
//通过输出流把他写到byte[] 里面去
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
is = new FileInputStream(file);
int tmp = 0;
while ((tmp = is.read()) != -1){
os.write(tmp);
}
returnData = os.toByteArray();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (is == null) {
is.close();
}
if (os == null) {
os.close();
}
}catch (Exception e2){}
}
return returnData;
}
@Override
public String toString() {
return this.name;
}
}
package ClassLoader;
/**
* @ Author :xuefeng
* @ Date :2019/2/27 5:24 PM
*/
public class TestDemo {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
MyClassLoader aloader = new MyClassLoader("小冷","/Users/lengxuefeng/Documents/code/xuefeng/");
//null 就是 BootStrap ClasserLoader 加载器 不是null就是有父类加载器 会先加载父类加载器
//这里的父类加载器是aloader aloader当前的父加载器就是b Demo
MyClassLoader bloader = new MyClassLoader(aloader,"小明","/Users/lengxuefeng/Documents/code/xuefeng/");
Class<?> aClass = bloader.loadClass("ClassLoader.Demo");//b Demo sun.misc.Launcher$AppClassLoader@18b4aac2 本项目的文件
// Class<?> aClass = bloader.loadClass("ClassLoderDemoFile.Demo");//A Demo 本地的文件
aClass.newInstance();
}
}
package ClassLoader;
/**
* @ Author :xuefeng
* @ Date :2019/2/27 5:45 PM
*/
public class Demo {
public Demo(){
System.out.println("b Demo "+this.getClass().getClassLoader());
}
}
demo地址:https://gitee.com/xuefengo/xfdemo.git
视频链接:https://pan.baidu.com/s/130iuFxW8ToQsjLNQTf_DcA 密码:ct3y