Java中import和class.forName之间的区别 [英] Difference Between import and class.forName in java

查看:335
本文介绍了Java中import和class.forName之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import和class.forName都加载类文件. 当我举一个在jsp文件中导入mysql数据的示例时,需要通过class.forName导入驱动程序类.当我通过import语句导入jdbc驱动程序时,它无法从tomcat服务器中的mysql中获取数据.

Both import and class.forName loads the class file. When I do an example of importing a mysql data in jsp file, It is needed to import the driver class through class.forName .when I import the jdbc driver through import statement it cant take data from mysql in tomcat server .

推荐答案

1 : import 
==> loads the class when you call any instance of it or call anything by class reference
==> loads the class when call is made

2 : Class.forName("");
==> loads the class in the jvm immediately

可以看出差异 如果一个类有静态块

difference can be seen by if a class has static block

==> import will not call the static block
==> Class.forName("") will call the static block

以您的情况

===> Driver class when loaded by Class.forName("") , executes its static block , which published the driver
==> Simply importing the Driver class wont execute the static block and thus your Driver will not be published for connection objects to be created

这篇关于Java中import和class.forName之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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