1.从google搜到的资料显示Class.forName()会执行类的初始化操作,static区域会被执行,ClassLoader.loadClass()不会执行初始化操作
只是加载类时会有区别,但是执行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.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);
}