自定义类加载器深入详解+类加载重要方法详解
public class MyTest16 extends ClassLoader{
private String classLoaderName;
private final String fileExtension = ".class";
public MyTest16(String classLoaderName){
super();
this.classLoaderName = classLoaderName;
}
public MyTest16(ClassLoader parent, String classLoaderName){
super(parent);
this.classLoaderName = classLoaderName;
}
@Override
public String toString() {
return "[" + this.classLoaderName + "]";
}
@Override
protected Class<?> findClass(String className) throws ClassNotFoundException {
byte[] data = this.loadClassData(className);
return this.defineClass(className,data,0,data.length);
}
private byte[] loadClassData(String className){
InputStream is = null;
byte[] data = null;
ByteArrayOutputStream baos = null;
try {
this.classLoaderName = this.classLoaderName.replace(".","/");
is = new FileInputStream(new File(className + this.fileExtension));
int ch;
while (-1 != (ch=is.read())){
baos.write(ch);
}
data = baos.toByteArray();
}catch (Exception ex){
ex.printStackTrace();
}finally {
try {
baos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
public static void test(ClassLoader classLoader) throws Exception {
Class<?> clazz = classLoader.loadClass("Jvm.MyTest10");
Object object = clazz.newInstance();
System.out.println(object);
}
public static void main(String[] args) throws Exception {
MyTest16 loader1 = new MyTest16("loader1");
test(loader1);
}
}
运行结果:
MyTest10 static block
Jvm.MyTest10@6d6f6e28 <--- MyTest10已经被加载了