自定义类加载器classLoader

package cn.bdqn.userconsumer;

import java.io.*;

/**
* 自定义classLoader 类加载器
*/
public class HelloClassLoad extends ClassLoader {

/**
* 自定义类加载器
* 继承classLoader 重写findClass()方法
* @param name
* @return
* @throws ClassNotFoundException
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
File file = new File("F:\\test",name.replace(".","\\").concat(".class"));
try {
FileInputStream inputStream = new FileInputStream(file);
//FileOutputStream fileoutput = new FileOutputStream(new File("F:/test",name.replace(".","/").concat(".class")));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int by=0;
while((by = inputStream.read()) !=0){
outputStream.write(by);
}

byte[] bytes = outputStream.toByteArray();
outputStream.close();

defineClass(name,bytes,0,bytes.length);
} catch (Exception e) {
e.printStackTrace();
}

return super.findClass(name);
}


public static void main(String[] args) {
try {
//使用自定义 classLoader
ClassLoader classLoader = new HelloClassLoad();
//加载指定目录下的类文件
Class<?> aClass = classLoader.loadClass("cn.bdqn.userconsumer.HelloJol");
HelloJol helloJol = (HelloJol) aClass.newInstance();
helloJol.Str();
System.out.println(classLoader.getClass().getClassLoader());
System.out.println(classLoader.getParent());
} catch (Exception e) {
e.printStackTrace();
}
}







}
posted @ 2021-05-27 22:52  徒手攀岩  阅读(144)  评论(0编辑  收藏  举报