简体   繁体   中英

What ClassLoader does Class.forName use by default?

I had the impression that Class.forName(String className) used the Thread.currentThread().getContextClassLoader() to load the class but apparently that isn't the case.

Hence my question, what ClassLoader does Class.forName use by default? is it the ClassLoader.getSystemClassLoader() ?

and what's the difference between Thread.currentThread().getContextClassLoader() and ClassLoader.getSystemClassLoader() ?

It uses the caller's classloader. From the documentation :

Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to:

 Class.forName(className, true, currentLoader) 

where currentLoader denotes the defining class loader of the current class.

It uses invokers class loader. The source code of the forName(), :

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

And the getCallerClassLoader() is :

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();
    }

And the description of this method is :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM