本文介绍了Class.forName() 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解了 java.sql 包.它使用Class.forName() 来动态加载扩展DriverManager 的驱动程序.然后我们使用 DriverManager.getConnection() 方法获取连接.

那么整个事情是如何运作的?
DriverManager 类如何知道如何在不使用实际驱动程序的类名的情况下获取连接.

我们也可以将 Class.forName() 用于自定义应用程序...如果能用一个例子来解释这一点,我会很高兴.

解决方案

Class.forName 只是加载一个类,包括运行它的静态初始化器,像这样:

class Foo {静止的 {System.out.println("Foo 初始化");}}公共类测试{public static void main(String [] args) 抛出异常 {Class.forName("Foo");}}

您正在谈论的所有其余过程都是特定于 JDBC 的.驱动程序 - 实现 Driver,它不扩展 DriverManager - 只需使用 DriverManager.registerDriver 注册一个适当的实例.然后当DriverManager需要为特定的连接字符串寻找驱动时,它会依次调用每个注册的驱动上的connect,直到成功并返回一个非空的连接.>

请注意,这种注册驱动程序的方式相当老式 - 查看 DriverManager 获取更现代的数据源获取方式.

I just learned about java.sql package. It uses Class.forName() to dynamically load the driver which extends DriverManager.Then we get connection using DriverManager.getConnection() method.

So how does the entire thing work?
How does DriverManager class know how to get the connection without using class name of the actual driver.

Also can we use Class.forName() for custom applications... if this is explained with an example I will be very happy.

解决方案

Class.forName simply loads a class, including running its static initializers, like this:

class Foo {
    static {
        System.out.println("Foo initializing");
    }
}

public class Test {
    public static void main(String [] args) throws Exception {
        Class.forName("Foo");
    }
}

All the rest of the procedure you're talking about is JDBC-specific. The driver - which implements Driver, it doesn't extend DriverManager - simply registers an appropriate instance using DriverManager.registerDriver. Then when DriverManager needs to find a driver for a particular connection string, it calls connect on each registered driver in turn until one succeeds and returns a non-null connection.

Note that this way of registering drivers is reasonably old-fashioned - look at the docs for DriverManager for more modern ways of getting at a data source.

这篇关于Class.forName() 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:10