Reputation: 694
In context of making a database Connection, we normally import the required packages and use Class.forName() to load the required Driver classes by the classloader of the calling class.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
....
....
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(...);
Can not we simply drop off the Class.forName() as in this:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.*;
....
....
Connection con=DriverManager.getConnection(...);
My question is when the dependencies of a class are loaded by the same classloader that loaded the dependent class, by the same mechanism used with Class.forName(className) implicitly, the why to give Class.forName() explicitly. Just include the driver class in import statement. Will the driver class not automatically loaded when it incounters the DriverManager.getConnection() line? com.mysql.jdbc package is in import statement. Or do i need to add al line like
Class clazz=com.mysq.jdbc.Driver.class
to trigger the Class.forName() .
Upvotes: 2
Views: 3367
Reputation: 13858
As long as your driver is JDBC 4.0 compliant, you don't need the Class.forName()
.
Please read the introduction on DriverManager JavaDoc for how this has been handled.
Of cause, the driver still needs to be on the classpath. Which was true for Class.forName()
as well (would've thrown ClassNotFoundException
otherwise)
Upvotes: 2
Reputation: 691685
First, loading the driver class shouldn't be necessary anymore, because Java has a built-in service provider loading mechanism that looks in the jar files in the classpath to find available drivers.
Just importing a class is not sufficient to load it. All an import does is allow you, at compile time, to refer to the class using its simple name rather than its fully qualified name. But if you never actually load the class, it won't do anything.
You could indeed load the class without using reflection, but that means that you need to have tthe driver as a compile-time dependency, which is often unwanted: you shouldn't rely on database-specific classes from the driver, but only on standard JDBC interfaces. Not having the driver in the compile classpath makes that sure.
Upvotes: 4
Reputation: 262484
An import
statement does not do anything at run-time. It is not even part of the compiled class. It just tells the compiler where to look for stuff.
A line like Class<?> dummy = com.mysql.jdbc.Driver.class
will work, but then you have a compile-time dependency on the MySQL driver JAR file (which Class.forName does not have, but may not be a bad thing in the grand scheme of things).
Upvotes: 2