08 虚拟机类加载机制

2020-09-16  本文已影响0人  格林哈

1 类加载机制

1.1 类的生命周期

java虚拟机规范 严格规定了6种情况必须立即进行初始化。

1.2 类加载的过程

1.3 验证

1.4 准备

1.5 解析

1.6 初始化

public class Test {
    static {
        i = 0;  //  给变量复制可以正常编译通过
        System.out.print(i);  // 这句编译器会提示“非法向前引用”
    }
    static int i = 1;
}

2 类加载器

2.1 类与类加载器

public class ClassLoaderTest {

    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("com.mg.javaxnj.chapter07.ClassLoaderTest").newInstance();

        System.out.println(obj.getClass());
        System.out.println(obj instanceof  com.mg.javaxnj.chapter07.ClassLoaderTest);
        System.out.println(obj.getClass().getClassLoader());
        System.out.println(com.mg.javaxnj.chapter07.ClassLoaderTest.class.getClassLoader());
    }
}

// 输出
class com.mg.javaxnj.chapter07.ClassLoaderTest
false
com.mg.javaxnj.chapter07.ClassLoaderTest$1@4f023edb
sun.misc.Launcher$AppClassLoader@18b4aac2

2.2 双亲委派模型

三层类加载器
双亲委派模型的工作过程
破坏双亲委派模型
上一篇 下一篇

猜你喜欢

热点阅读