版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
类加载机制概念
类加载器主要负责将class加载进jvm内存中,然后才能new出对象
三种加载器层次关系
三种加载器,负责加载的类路径
类加载器的工作流程
- 简单来说就是jvm遇到需要加载的类时,就先向app loader说要要加载这个类,然后不断向上传递,直到boostrap这个,
然后,去类加载器的路径下寻找这个class,如果没找到,然后再让下一个加载器去加载
自定义类加载器
示例代码加载器
public class CustomClassLoaderDemo extends ClassLoader {
@Override
public Class<?> findClass(String name) {
byte[] bt = loadClassData(name);
return defineClass(name, bt, 0, bt.length);
}
// 从class文件中
private byte[] loadClassData(String className) {
//read class
InputStream is = getClass().getClassLoader().getResourceAsStream(className.replace(".", "/")+".class");
ByteArrayOutputStream byteSt = new ByteArrayOutputStream();
//write into byte
int len =0;
try {
while((len=is.read())!=-1){
byteSt.write(len);
}
} catch (IOException e) {
e.printStackTrace();
}
//convert into byte array
return byteSt.toByteArray();
}
}
测试类
public class Test {
public void show(){
System.out.println("Hello World!");
}
}
主类
public class MainClass {
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
CustomClassLoaderDemo loader = new CustomClassLoaderDemo();
Class<?> c = loader.findClass("com.concretepage.lang.Test");
Object ob = c.newInstance();
Method md = c.getMethod("show");
md.invoke(ob);
}
}