关于Class.forName(String str)的理解

学习Hibernate,然后从头开始,看到JDBC片,开头就是一个Class.forName,一直不知道怎么回事,只是知道是加载驱动,但是具体情况不得而知,今天研究了一下,搜索了一些资料终于搞清楚了。

参考网址:http://dustin.iteye.com/blog/44291

废话不说,上代码,里面有解释:

package com.ClassForName;

//操作类
class StaticClass {
	static {
		System.out.println("this is StaticClass's Static region.");
	}
}

// 测试类
public class TestFormName {
	public static void main(String[] args) {
		// 1、先定义类,但是不初始化,因为StaticClass类被加载到JVM中,但是没有初始化
		// StaticClass sc = null;
		// 2、定义并初始化类,StaticClass类被加载到JVM中,而且已经被初始化
		// StaticClass sc2 = new StaticClass();
		try {
			// 3、和【2】类似,如果想获得类实例则使用4
			Class.forName("com.ClassForName.StaticClass");
			// 4、获得实例
			StaticClass sc3 = (StaticClass) (Class
					.forName("com.ClassForName.StaticClass").newInstance());

			// 5、Class.forName("com.mysql.jdbc.Driver");
			// String url =
			// "jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8";
			// String user = "";
			// String psw = "";
			// 6、Connection con = DriverManager.getConnection(url,user,psw);
			// 而【5】的作用和上述一样,只是将类加载到JVM中并且初始化,所谓的
			// 初始化就是相当于【2】一样,执行该类的static部分,包括static字段和static块,
			// 而Driver类已经自动注册到DriverManager上面,所以我们才可以调用【6】,
			//这其中com.mysql.jdbc.Driver的static块帮我们做了一件事情:把自身注册到DriverManager上面。
			// 下面是Driver类的部分源码:
			/*
			 * package com.mysql.jdbc public class Driver extends
			 * NonRegisteringDriver implements java.sql.Driver { // ~ Static
			 * fields/initializers //
			 * --------------------------------------------- // // Register
			 * ourselves with the DriverManager // static { try { //这里帮助我们注册了
			 * java.sql.DriverManager.registerDriver(new Driver()); } catch
			 * (SQLException E) { throw new
			 * RuntimeException("Can't register driver!"); } } // ~ Constructors
			 * // -----------------------------------------------------------
			 * /** Construct a new driver and register it with DriverManager
			 * 
			 * @throws SQLException if a database error occurs.
			 */
			/*
			 * public Driver() throws SQLException { // Required for
			 * Class.forName().newInstance() } }
			 */
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}

 对于JVM从来没有深入的了解过,现在看来,是时候需要研究一下了。

2012.08.16 写在京东+苏宁大战第一天后

原文地址:https://www.cnblogs.com/fiteg/p/2641932.html