日期:2014-05-17  浏览次数:20743 次

Class.forName("org.gjt.mm.mysql.Driver").newInstance();



Class.forName("org.gjt.mm.mysql.Driver").newInstance();



Class.forName("org.gjt.mm.mysql.Driver")

有什么区别呢?
;



------解决方案--------------------
Class.forName("org.gjt.mm.mysql.Driver")
可以导致加载类,返回值是Class类对象

Class.forName("org.gjt.mm.mysql.Driver").newInstance();
除了导致加载类,还会生成相应的Driver对象事例,即返回值是Object对象(实际上是Driver对象)
------解决方案--------------------
为什么需要Class.forName("org.gjt.mm.mysql.Driver")呢?看org.gjt.mm.mysql.Driver里的static块
------解决方案--------------------
public static Class<?> forName(String className)
throws ClassNotFoundException
Returns the Class object associated with the class or interface with the given string name.

看方法返回类型Class,与className所表示的类或接口关联



public T newInstance()
throws InstantiationException,
IllegalAccessException
Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.

创建这个Class对象所表示的类的新实例。会被重新实例化,如果未初始化就还会被初始化。(貌似还有forName后未被初始化的情形啊)
------解决方案--------------------
前者是把类的字节码加载在虚拟机上,如果该类有static变量啊,static代码块,则会被执行
后者干了前者的事,还根据字节码new出一个对象。

mysql里面的文档是用的第一种,其实那家伙脑残,根本不用new一个对象。
------解决方案--------------------
对头,加载驱动,驱动类会在static块中生成driver实例并注册到DriverManager中
探讨
为什么需要Class.forName("org.gjt.mm.mysql.Driver")呢?看org.gjt.mm.mysql.Driver里的static块

------解决方案--------------------
探讨

public static Class<?> forName(String className)
throws ClassNotFoundException
Returns the Class object associated with the class or interface with the given string name.

……

------解决方案--------------------
探讨
public static Class<?> forName(String className)
throws ClassNotFoundException
Returns the Class object associated with the class or interface with the given string name.

看方法返回类型Class,与classNam……

------解决方案--------------------
请使用第二种,第一种纯属没事找抽型!

PS:MySQL 的 JDBC 驱动 org.git.mm.mysql.Driver 驱动是其作者 Mark Matthews 在加入 MySQL 公司之前的驱动(包名中的 mm 就是作者的名字缩写)。

这个驱动在 Mark Matthews 加入 MySQL 之后就已经弃用了,现在应该使用 com.mysql.jdbc.Driver 这个驱动,而 org.git.mm.mysql.Driver 仅为了兼容性而保留,MySQL 今后也不会对其更新或者添加新的功能了。