更好的理解 - Class.forName(" com.mysql.jdbc.Driver")。newInstance(); [英] Better understaning - Class.forName("com.mysql.jdbc.Driver").newInstance ();

查看:71
本文介绍了更好的理解 - Class.forName(" com.mysql.jdbc.Driver")。newInstance();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个有用的链接代码,更新时可以很好地工作以击中我的Web服务器。我绝对可以做到一切。

I came across this helpful link with code which works perfectly when updated to hit against my web server. I can do absolutely everything.

现在,我唯一不能完全理解的是 Class.forName()

Now, the only thing I do not fully understand is the Class.forName().

为什么要使用它?可以这样做吗?这是一个解决其他问题的工作吗?添加参考?创建一个类来实现/扩展另一个?

Why is this being used? Can this be done differently? Is this a work around for something else? Adding a reference? Creating a class as implementing/extending another one?

我想完全理解发生了什么,但这是我的方式。

I want to fully understand what is going on, but this is in my way.

谢谢

推荐答案

该代码强制表示MySQL驱动程序的类加载和初始化。在Java中,除非必需该类被加载,否则不会加载类。由于JDBC代码通常永远不会直接引用驱动程序,因此如果没有 Class.forName (或其他一些等效的替代方法),它就不会加载。

That code is forcing the class representing the MySQL driver to load and initialize. In Java, a class is not loaded unless it is necessary that the class gets loaded. Since JDBC code usually never directly references the driver, it wouldn't get loaded without Class.forName (or some other equivalent alternatives).

请注意,加载初始化类是必要的,这是两个不同的东西。

Note that it is necessary to both load and initialize the class, which are 2 different things.

另外,请注意,没有必要调用 .newInstance() - 驱动程序的静态初始值设定项已经将自己注册为JDBC驱动程序。

Also, note that it is not necessary to call .newInstance() -- the static initializer of the Driver already registers itself as a JDBC driver.

最后,请注意,使用 Service Loader API 时,通常不需要调用Class.forName( )加载驱动程序:它可以自动加载。

Finally, note that with the Service Loader API it is usually not necessary to call Class.forName() to load the driver: it can be loaded automatically.

这篇关于更好的理解 - Class.forName(" com.mysql.jdbc.Driver")。newInstance();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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