ClassLoader的loadClass方法源码浅析

protected synchronized Class<?> loadClass(String name, boolean resolve)
	throws ClassNotFoundException
    {
	// First, check if the class has already been loaded
	Class c = findLoadedClass(name);
	if (c == null) {
	    try {
		if (parent != null) {
		    c = parent.loadClass(name, false);
		} else {
		    c = findBootstrapClassOrNull(name);
		}
	    } catch (ClassNotFoundException e) {
                // ClassNotFoundException thrown if class not found
                // from the non-null parent class loader
            }
            if (c == null) {
	        // If still not found, then invoke findClass in order
	        // to find the class.
	        c = findClass(name);
	    }
	}
	if (resolve) {
	    resolveClass(c);
	}
	return c;
    }


用loadClass指定二进制名称加载类的步骤:

findLoadedClass - parent.loadClass - findClass

首先是findLoadedClass(),如果类已经被JVM加载并初始化则返回此类的Class对象,否则,判定是否有父类加载器,有则通过父类加载器loadClass(),无则使用jvm内置类加载器findBootstrapClassOrNull(name)。
若通过父类加载器都无法找到Class类对象,则使用findClass()方法。findClass若要使用,鼓励在子类中重新,而不是直接调用。

附加一段java reflection in action原话:
Java programmers are strongly encouraged to override findClass rather than
loadClass, because the implementation of  loadClass defined by  ClassLoader
supports the delegation model. It is possible to override  loadClass, but this is
bad form.

你可能感兴趣的:(ClassLoader)