文章目录
- 类加载器
- 类加载器分类
- 自定义类加载器
- 双亲委派模型
类加载器
类加载器分类
自定义类加载器
- 步骤:
自定义个类加载器代码:
public class ClassLoaderDemo {
public static void main(String[] args) throws Exception {
ClassLoader myLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
String fileName = name.substring(name.lastIndexOf(".")+ 1) + ".class";
InputStream is = getClass().getResourceAsStream(fileName);
if (is == null) {
return super.loadClass(name);
}
byte[] b = new byte[is.available()];
is.read(b);
return defineClass(name, b, 0, b.length);
} catch (IOException e) {
throw new ClassNotFoundException(name);
}
}
};
Object obj = myLoader.loadClass("jvm.demo4.ClassLoaderDemo").newInstance();
System.out.println(obj.getClass());
System.out.println(obj instanceof ClassLoaderDemo);
}
}
结果:
双亲委派模型
这么多的类加载器如何协同工作呢?
写个测试代码:
报错信息
明明有main,报没有?那是因为java.lang.Object在rt包中,也就是使用的是默认的启动类加载器,没有用我们写的Object对象,默认的rt包下Object类没有main方法,所以报错上图。
完