Class.forName默认使用什么ClassLoader?

时间:2012-06-22 08:17:46

标签: java classloader

我的印象是Class.forName(String className)使用Thread.currentThread().getContextClassLoader()来加载课程,但显然情况并非如此。

因此,我的问题默认情况下ClassLoader Class.forName使用了什么?它是ClassLoader.getSystemClassLoader() 吗?

Thread.currentThread().getContextClassLoader()ClassLoader.getSystemClassLoader()之间有什么区别?

2 个答案:

答案 0 :(得分:7)

它使用调用者的类加载器。来自the documentation

  

返回与具有给定字符串名称的类或接口关联的Class对象。调用此方法等同于:

Class.forName(className, true, currentLoader)
     

其中currentLoader表示当前类的定义类加载器。

答案 1 :(得分:1)

它使用调用者类加载器。 forName()的源代码:

public static Class<?> forName(String className) 
                throws ClassNotFoundException {
        return forName0(className, true, ClassLoader.getCallerClassLoader());
    }

getCallerClassLoader()是:

static ClassLoader getCallerClassLoader() {
        // NOTE use of more generic Reflection.getCallerClass()
        Class caller = Reflection.getCallerClass(3);
        // This can be null if the VM is requesting it
        if (caller == null) {
            return null;
        }
        // Circumvent security check since this is package-private
        return caller.getClassLoader0();
    }

这种方法的描述是:

// Returns the invoker's class loader, or null if none.