打印

[转帖] JAVA知识:Class.forName的含义

JAVA知识:Class.forName的含义

复制内容到剪贴板
代码:
Class aClass = Class.forName(xxx.xx.xx);
Object anInstance = aClass.newInstance();
Class.forName("").newInstance()返回的是object
but there is some limit for this method to create instance
that is your class constructor should no contain parameters,
and you should cast the instance manually.
Class Driver{
protected static Driver current;
public static Driver getDriver(){
return current;
}
}
Class MyDriver extends Driver{
static{
Driver.current=new MyDriver();
}
MyDriver(){}
}
用时:
复制内容到剪贴板
代码:
Class.forName("MyDriver");
Driver d=Driver.getDriver();
  有的jdbc连接数据库的写法里是Class.forName(xxx.xx.xx);而有一些:Class.forName(xxx.xx.xx)。newInstance(),为什么会有这两种写法呢?


  Class.forName(xxx.xx.xx) 返回的是一个类,

  。newInstance() 后才创建一个对象

  Class.forName(xxx.xx.xx);的作用是要求JVM查找并加载指定的类,也就是说JVM会执行该类的静态代码段

  在JDBC规范中明确要求这个Driver类必须向DriverManager注册自己,即任何一个JDBC Driver的Driver类的代码都必须类似如下:
复制内容到剪贴板
代码:
public class MyJDBCDriver implements Driver {
static {
DriverManager.registerDriver(new MyJDBCDriver());
}
}
  所以我们在使用JDBC时只需要Class.forName(XXX.XXX);就可以了

  在JDBC驱动中,有一块静态代码,也叫静态初始化块,它执行的时间是当class调入到内存中就执行(你可以想像成,当类调用到内存后就执行一个方法)。所以很多人把jdbc driver调入到内存中,再实例化对象是没有意义的。
个人迅雷博客资源,欢迎下载扔花:
微软TechNet中文广播: Windows Server 2008实战攻略系列(全18讲)
Wolf 2007年郑Sir IE授课视频(全29讲)

微软常用资源:
微软TechNet虚拟实验室
微软TechNet中文网络广播
微软客服电话:
108008520952 (North China)
108001520952 (South China)

TOP