开发者

Why java need Class.forName or dynamic loading?

开发者 https://www.devze.com 2023-04-05 03:59 出处:网络
Say. jdbc driver need Class.forName to exec static block of a开发者_StackOverflow class. Why not just run it as a class field?Class.forName() is guaranteed to initialize the class at the time you call

Say. jdbc driver need Class.forName to exec static block of a开发者_StackOverflow class. Why not just run it as a class field?


Class.forName() is guaranteed to initialize the class at the time you call it. How would you propose to do it? Could you just declare a local variable without assigning it, like com.foo.Driver d;? What about a making it a member variable instead? Would you have to actually assign it? What does the spec say about how and when a class has to be loaded? Do you really want to have to think about that, or just call Class.forName()?

On a related note, it's no longer necessary to do this with many JDBC drivers. The DriverManager now uses the ServiceLoader mechanism to identify and load conforming driver classes.


The whole idea of JDBC is to not be dependant on one specific driver or implementation. The idea is you can use JDBC and configure at runtime any driver which is available. To do this you need to load the driver by name and use the JDBC methods. Unfortunately JDBC doesn't abstract away all the differences between databases like error codes, and switching to a database you haven't tested may not be a good idea.

You could take the view that for all of your libraries, you have them available at compile time and you wouldn't change the database on a wim, without a minimum re-testing and re-deploying your application. In this case linking to a specific driver (instead of using Class.forName) might be a good thing because it would force you (or whomever does this) to put more thought into the change and follow your testing procedures.


It's impractical to use technique for loading JDBC drivers other than reflection. (Though there are different ways to do it). There's a lot of JDBC drivers and the implementation code may not be available to the app.

0

精彩评论

暂无评论...
验证码 换一张
取 消