Class.forName()如何工作? [英] How does Class.forName() work?

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

问题描述

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

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.

那么整个事情是怎么回事work $

如何在不使用实际驱动程序的类名的情况下知道如何获取连接。

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.

我们也可以使用Class.forName ()对于自定义应用程序...如果用一个例子解释我会非常高兴。

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

推荐答案

Class.forName 只需加载一个类,包括运行其静态初始值设定项,如下所示:

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");
    }
}

您正在谈论的所有其余程序是特定于JDBC的。驱动程序 - 实现驱动程序,它不扩展 DriverManager - 只需使用<$ c $注册一个适当的实例C> DriverManager.registerDriver 。然后当 DriverManager 需要查找特定连接字符串的驱动程序时,它会依次调用每个注册驱动程序上的 acceptsURL ,直到一个人说,是的,我可以成为这种联系的驱动力。

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 acceptsURL on each registered driver in turn until one says, "Yes, I can be the driver for that connection."

请注意,这种注册驱动程序的方式相当老套 - 请查看< a href =http://download.oracle.com/javase/6/docs/api/java/sql/DriverManager.html =noreferrer> DriverManager 以更现代的方式获取数据源。

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()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆