自定义类加载器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();
}
}







}
上一篇:专题1:反射机制


下一篇:java.lang.NoClassDefFoundError: javax/servlet/ServletOutputStream 报错解决