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

1.从google搜到的资料显示Class.forName()会执行类的初始化操作,static区域会被执行,ClassLoader.loadClass()不会执行初始化操作

http://stackoverflow.com/questions/4285855/difference-betweeen-loading-a-class-using-classloader-and-class-forname

只是加载类时会有区别,但是执行newInstance()两者是没有区别的,都是会初始化类

public class TestInterface {
	static {
		System.out.println("this is static field, TestInterface");
	}
}

class Test extends TestInterface {
	static {
		System.out.println("this is static field, Test");
	}
}
Class.forName

Class.forName("com.test.Test").newInstance();
System.out.println("after class.forname");

Console:
this is static field, TestInterface
this is static field, Test
after class.forname


ClassLoader.loadClass
ClassLoader.getSystemClassLoader().loadClass("com.test.Test").newInstance();
System.out.println("after loadclass");

Console:
this is static field, TestInterface
this is static field, Test
after loadclass

2.以mysql JDBC Driver这个来看两者的区别

java连接mysql示例

 //第一步:加载MySQL的JDBC的驱动
        Class.forName("com.mysql.jdbc.Driver");
        
        //取得连接的url,能访问MySQL数据库的用户名,密码;studentinfo:数据库名
        String url = "jdbc:mysql://localhost:3306/studentinfo";        
        String username = "root";
        String password = "admin";
        
        //第二步:创建与MySQL数据库的连接类的实例
        Connection con = DriverManager.getConnection(url, username, password);


com.mysql.jdbc.Driver

package com.mysql.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

public class Driver
  extends NonRegisteringDriver
  implements java.sql.Driver
{
  public Driver()
    throws SQLException
  {}
  //如果在客户端代码中使用ClassLoader.loadClass这种方法就不会执行static域,就不会向DriverManager注册该驱动
  static
  {
    try
    {
      DriverManager.registerDriver(new Driver());
    }
    catch (SQLException E)
    {
      throw new RuntimeException("Can't register driver!");
    }
  }
}
DriverManager.class主要涉及的代码

public static Connection getConnection(String url)
        throws SQLException {
...
        return (getConnection(url, info, Reflection.getCallerClass()));
    }

private static Connection getConnection(
        String url, java.util.Properties info, Class<?> caller) throws SQLException {
...//如果registeredDrivers为空 
for(DriverInfo aDriver : registeredDrivers) {
	Connection con = aDriver.driver.connect(url, info);
...}
return (con);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值