转载

Java Class.forName() 与 ClassLoad

2017-01-06  本文已影响191人  专职跑龙套

类的显示加载 VS 类的隐式加载

ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class c = cl.loadClass("Student");

Class.forName() VS ClassLoader.loadClass()

关于 Class.forName(),其代码如下:

    public static Class<?> forName(String className)
                throws ClassNotFoundException {
        Class<?> caller = Reflection.getCallerClass();
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }

其中 forName0() 方法调用中的参数 true 表示要初始化该类。包括:

关于类的初始化,具体参见 Java 类的加载,链接,初始化

关于 ClassLoader.loadClass(),其代码如下:

    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }

其中 loadClass() 方法调用中的参数 false 表示这个类加载后不需要去链接。

总结

上一篇下一篇

猜你喜欢

热点阅读