Reputation:
Is it correct that when we dynamically load a .class class file, we need to use reflection to access the methods defined in the class?
When we use a JDBC driver in our Java program,
import java.sql
and access the classes and methods defined in the java.sql
.Under the hood, is there reflection undergoing? If not, how does it work without reflection?
In general, when we dynamically load a .java class file, how can we eliminate or hide the use of reflection to access the methods defined in the class, just like a JDBC driver?
By the way, does a JDBC driver define exactly a class?
Thanks.
Upvotes: 1
Views: 617
Reputation: 44952
JDBC driver needs to implement java.sql.Driver
interface (e.g. oracle.jdbc.OracleDriver
). Apart from that the JDBC driver code is just plain Java code. It can use reflection or any other Java language feature. It's up to the driver vendor to decide if it's worth it e.g. using classes introduced in Java 8 will make it compatible only with Java 8+.
What is and isn't dynamically loaded depends on the JVM and the implementation of ClassLoader
. Certain technologies like OSGI give more flexibility by implementing a ClassLoader
that allows for unloading parts of the application.
Loading the JDBC driver class should happen so infrequently, and be cached by JVM, that cost of this one reflective call to load the driver should be negligible. A single SELECT 1
query will be orders of magnitude more expensive than loading the driver bytecode.
Upvotes: 2
Reputation: 726569
Starting with JDBC 4.0 it is no longer necessary to do any reflection-related calls to work with JDBC drivers, as any driver discovered on your class path is loaded automatically.
If your code must support pre-JDBC 4 code, or if your JDBC driver is not located on your class path, you must call Class.forName
to load the driver.
Under the hood, is there reflection undergoing?
JDBC 4.0 uses Service Provider mechanism to locate JDBC drivers without doing reflection directly. At some point, however, JDBC driver class needs to be loaded, so a reflection call must be performed.
Upvotes: 1