ClassLoader.loadClass()与Class.forName()的区别

1.Class.forName

先直接上源码

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

/**
	 * @param name       fully qualified name of the desired class
     * @param initialize if {@code true} the class will be initialized.
     *                   See Section 12.4 of The Java Language Specification.
     * @param loader     class loader from which the class must be loaded
     * @return           class object representing the desired class
     *
     * @exception LinkageError if the linkage fails
     * @exception ExceptionInInitializerError if the initialization provoked
     *            by this method fails
     * @exception ClassNotFoundException if the class cannot be located by
     *            the specified class loader
     *
     * @see       java.lang.Class#forName(String)
     * @see       java.lang.ClassLoader
     * @since     1.2
     */
    @CallerSensitive
    public static Class<?> forName(String name, boolean initialize,ClassLoader loader)
        throws ClassNotFoundException{
     }

由上面源码可以看出:
Class.forName(“className”)方法调用forName(String name, boolean initialize,ClassLoader loader),传入第二个默认参数为true。可以看到第二个参数的注释param initialize if true the class will be initialized,如果为true则class会初始化。

2.ClassLoader.loadClass()

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

protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException{
     }

ClassLoader.getSystemClassLoader().loadClass() 方法调用**loadClass(String name, boolean resolve)**第二个参数默认传入false,该参数表示目标对象被装载后不进行链接,这就意味这不会去执行该类静态块中间的内容。因此2者的区别就显而易见了。

你可能感兴趣的:(java,java)