加载 JDBC 驱动程序
我被告知加载 JDBC 驱动程序的首选方法是:
Class.forName(driverName);
我知道这对于从 XML 配置文件或用户输入读取的多个驱动程序之间的动态决策更好。我很好奇的是,调用此语句如何将指定的驱动程序加载到我们甚至不将生成的“Class”对象存储在任何地方的环境中。 JavaDocs 条目说:
public static Class forName(String className)
throws ClassNotFoundExceptionReturns
返回与给定字符串名称的类或接口关联的 Class 对象
在这种情况下,Java 开发人员如何仅通过此语句来促进驱动程序对象的存在?
I am told that the prefered method to load the JDBC driver is :
Class.forName(driverName);
I understand that this is better for a dynamic decision between multiple drivers maybe read from an XML config file or user input. The thing I am curious about is how does invoking this statement loads the stated driver into the environment where we are not even storing the resultant "Class" object anywhere. The JavaDocs entry says:
public static Class forName(String className)
throws ClassNotFoundExceptionReturns
returns the Class object associated with the class or interface with the given string name
In that case, how do the Java developers managed to facilitate the existence of driver object with merely this statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Class#forName()
运行 静态初始值设定项 (您知道,static
适用于类,而不适用于实例)。 JDBC 驱动程序实现应该在静态初始化器。请注意,存在有缺陷的 JDBC 驱动程序,例如 org.gjt.mm.mysql.Driver,它在构造函数中错误地注册了自己。这就是为什么您需要在此类驱动程序上调用
newInstance()
来让它们自行注册。The
Class#forName()
runs the static initializers (you know,static
applies to the class, not to the instance). The JDBC driver implementation should register itself in the static initializer.Note that there exist buggy JDBC drivers such as
org.gjt.mm.mysql.Driver
which incorrectly registers itself inside the constructor instead. That's why you need anewInstance()
call afterwards on such drivers to get them to register themselves.