java forname loader_在 Java 的反射中,Class.forName 和 ClassLoader 的区别

1. 解释

在java中Class.forName()和ClassLoader都可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“通过一个类的全限定名来获取描述此类的二进制字节流”,获取到二进制流后放到JVM中。Class.forName()方法实际上也是调用的CLassLoader来实现的。

Class.forName(String className)  的源码如下:

1 @CallerSensitive2 public static Class>forName(String className)3 throwsClassNotFoundException {4 Class> caller =Reflection.getCallerClass();5 return forName0(className, true, ClassLoader.getClassLoader(caller), caller);6 }

最后调用的方法是forName0这个方法,在这个forName0方法中的第二个参数被默认设置为了true,这个参数代表是否对加载的类进行初始化,设置为true时会类进行初始化,代表会执行类中的静态代码块,以及对静态变量的赋值等操作。

也可以调用Class.forName(String name, boolean initialize,ClassLoader loader)方法来手动选择在加载类的时候是否要对类进行初始化。Class.forName(String name, boolean initialize,ClassLoader loader)的源码如下:

1 /*@param name fully qualified name of the desired class2 * @param initialize if {@code true} the class will be initialized.3 * See Section 12.4 of The Java Language Specification.4 * @param loader class loader from which the class must be loaded5 * @return class object representing the desired class6 *7 * @exception LinkageError if the linkage fails8 * @exception ExceptionInInitializerError if the initialization provoked9 * by this method fails10 * @exception ClassNotFoundException if the class cannot be located by11 * the specified class loader12 *13 * @see java.lang.Class#forName(String)14 * @see java.lang.ClassLoader15 * @since 1.216 */

17 @CallerSensitive18 public static Class> forName(String name, booleaninitialize,19 ClassLoader loader)20 throwsClassNotFoundException21 {22 Class> caller = null;23 SecurityManager sm =System.getSecurityManager();24 if (sm != null) {25 //Reflective call to get caller class is only needed if a security manager26 //is present. Avoid the overhead of making this call otherwise.

27 caller =Reflection.getCallerClass();28 if(sun.misc.VM.isSystemDomainLoader(loader)) {29 ClassLoader ccl =ClassLoader.getClassLoader(caller);30 if (!sun.misc.VM.isSystemDomainLoader(ccl)) {31 sm.checkPermission(32 SecurityConstants.GET_CLASSLOADER_PERMISSION);33 }34 }35 }36 returnforName0(name, initialize, loader, caller);37 }

源码中的注释只摘取了一部分,其中对参数initialize的描述是:if {@code true} the class will be initialized.意思就是说:如果参数为true,则加载的类将会被初始化。

2. 举例

一个含有静态代码块、静态变量、赋值给静态变量的静态方法的类,如下:

1 public classClassForName {2

3 //静态代码块

4 static{5 System.out.println("执行了静态代码块");6 }7 //静态变量

8 private static String staticFiled =staticMethod();9

10 //赋值静态变量的静态方法

11 public staticString staticMethod(){12 System.out.println("执行了静态方法");13 return "给静态字段赋值了";14 }15 }

测试代码如下:

1 public classMyTest {2 @Test3 public voidtest44(){4

5 try{6 Class.forName("com.test.mytest.ClassForName");7 System.out.println("#########分割符(上面是Class.forName的加载过程,下面是ClassLoader的加载过程)##########");8 ClassLoader.getSystemClassLoader().loadClass("com.test.mytest.ClassForName");9 } catch(ClassNotFoundException e) {10 e.printStackTrace();11 }12

13 }14 }

运行结果:

1 执行了静态代码块2 执行了静态方法3 #########分割符(上面是Class.forName的加载过程,下面是ClassLoader的加载过程)##########

根据运行结果说明 Class.forName加载类是将类进了初始化,而ClassLoader的loadClass并没有对类进行初始化,只是把类加载到了虚拟机中。

3.应用场景

在我们熟悉的Spring框架中的IOC的实现就是使用的ClassLoader。

而在我们使用JDBC时通常是使用Class.forName()方法来加载数据库连接驱动。这是因为在JDBC规范中明确要求Driver(数据库驱动)类必须向DriverManager注册自己。

以MySQL的驱动为例解释:

1 public class Driver extends NonRegisteringDriver implementsjava.sql.Driver {2 //~ Static fields/initializers3 //---------------------------------------------4

5 //

6 //Register ourselves with the DriverManager7 //

8 static{9 try{10 java.sql.DriverManager.registerDriver(newDriver());11 } catch(SQLException E) {12 throw new RuntimeException("Can't register driver!");13 }14 }15

16 //~ Constructors17 //-----------------------------------------------------------

18

19 /**

20 * Construct a new driver and register it with DriverManager21 *22 *@throwsSQLException23 * if a database error occurs.24 */

25 public Driver() throwsSQLException {26 //Required for Class.forName().newInstance()

27 }28 }

我们看到Driver注册到DriverManager中的操作写在了静态代码块中,这就是为什么在写JDBC时使用Class.forName()的原因了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值