一尘不染

Java中import和class.forName之间的区别

jsp

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


阅读 312

收藏
2020-06-08

共1个答案

一尘不染

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

如果类具有静态块,则可以看出差异

==> 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
2020-06-08