ClassLoader和Class.forName()的区别

Java中Class.forName和classloader都可以用来对类进行加载。

  • Class.forName(“className”);

​ 其实这种方法调运的是:Class.forName(className, true, ClassLoader.getCallerClassLoader())方法
​ 参数一:className,需要加载的类的名称。
​ 参数二:true,是否对class进行初始化(需要initialize)
​ 参数三:classLoader,对应的类加载器

/**
* Returns the {@code Class} object associated with the class or interface with the given string name, using the given class loader.
* given the fully qualified name for a class or interface (in the same format returned by {@code getname}) this method attempts to locate, load, and link the class or interface.
* The specified class loader is used to load the class or interface.
* If the parameter {@code loader} is null, the class is loaded through the bootstrap class loader.
* The class is initialized only if the {@code initialize} parameter is {@code true} and if it has  not been initialized earlier.
*
* 使用给定的类加载器返回与具有给定字符串名称的类或接口关联的对象。
* 给定类或接口的完全限定名称(采用{@code getname}返回的相同格式),此方法尝试查找,加载和链接该类或接口。
* 指定的类加载器用于加载类或接口。如果参数{@code loader}为null,则通过引导类加载器加载该类
* 仅当{@code initialize}参数为{@code true}且之前尚未初始化时,才初始化该类。
*
* 

* {@code Class.forName("Foo")} * * * is equivalent to: * *

* {@code Class.forName("Foo", true, this.getClass().getClassLoader())} *
* * Note that this method throws errors related to loading, linking or * initializing as specified in Sections 12.2, 12.3 and 12.4 of
  • ClassLoader.laodClass(“className”);

​ 其实这种方法调运的是:ClassLoader.loadClass(name, false)方法
​ 参数一:name,需要加载的类的名称
​ 参数二:false,这个类加载以后是否需要去连接(不需要linking)

/**
* Loads the class with the specified binary name.
* The default implementation of this method searches for classes in the  following order:
*
* 用指定的二进制名称加载类.
* 此方法的默认实现按以下顺序搜索类.
*
* 
    * *

    Invoke {@link #findLoadedClass(String)} to check if the class has already been loaded. Invoke the {@link #findClass(String)} method to find the class. If the class was found using the above steps, and the

可见Class.forName除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。
而classloader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行static块。

你可能感兴趣的:(ClassLoader和Class.forName()的区别)