这是什么做Class.forName(“com.mysql.jdbc.Driver”)。newInstance(); [英] what exactly does this do Class.forName("com.mysql.jdbc.Driver").newInstance();

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

问题描述

在连接MySQL数据库时,我执行以下步骤:

  Connection con = null; 
Resultset rs = null;
语句st = null;
Class.forName(com.mysql.jdbc.Driver)。newInstance();
con = DriverManager.getConnection(jdbc:mysql:// localhost:3306 / database,root,passwp);

其实我想知道 Class.forName(com.mysql .jdbc.Driver)。newInstance(); 语句do。



Althogh这个类不在mysql.jar。 c> c>类 c>

java.lang包,所以它是用java分发的,并自动导入到每个类中。



forName()方法,只是返回类加载器加载的参数的 Class 对象。 newInstance()方法然后返回该类的一个新实例。



b $ b Class.forName(...)
它返回com.mysql.jdbc.Driver.class。
然后你会调用 newInstance(),返回类的实例,没有参数,所以它基本上是调用 new com .mysql.jdbc.Driver();


While connecting to MySQL database I do following steps

Connection con = null;
Resultset rs = null;
Statement st = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","passwp");

Actually I wanted to know what does Class.forName("com.mysql.jdbc.Driver").newInstance(); statement do.

Althogh this class is not in mysql.jar. Where is it present?

解决方案

The Class class is located in the java.lang package, so it is distributed with java, and imported automatically into every class.

What the forName() method does, is just return the Class object for the paramater that was loaded by the class loader. The newInstance() method then returns a new instance of the class.

So then what happens is you call Class.forName(...) it returns com.mysql.jdbc.Driver.class. You then call newInstance() on that class which returns an instance of the class, whith no paramaters, so it's basically calling new com.mysql.jdbc.Driver();.

这篇关于这是什么做Class.forName(“com.mysql.jdbc.Driver”)。newInstance();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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