From 76aed6ef732de38d82245b3d674f70bab30221e5 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Fri, 3 Jul 2015 22:31:49 -0400 Subject: Fuck it, serve the files directly. --- .html/java/stop-using-class-dot-forname.html | 155 +++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 .html/java/stop-using-class-dot-forname.html (limited to '.html/java/stop-using-class-dot-forname.html') diff --git a/.html/java/stop-using-class-dot-forname.html b/.html/java/stop-using-class-dot-forname.html new file mode 100644 index 0000000..85190e8 --- /dev/null +++ b/.html/java/stop-using-class-dot-forname.html @@ -0,0 +1,155 @@ + + + + + The Codex » + Stop Using Class Dot Forname + + + + + + + + +
+ + + + + +
+

JDBC Drivers and Class.forName()

+

The short version: stop using Class.forName(driverClass) to load JDBC +drivers. You don't need this, and haven't since Java 6. You arguably never +needed this.

+

This pattern appears all over the internet, and it's wrong.

+

Backstory

+

JDBC has more or less always provided two ways to set up Connection objects:

+
    +
  1. +

    Obtain them from a driver-provided DataSource class, which applications or + containers are expected to create for themselves.

    +
  2. +
  3. +

    Obtain them by passing a URL to DriverManager.

    +
  4. +
+

Most people start with the latter, since it's very straightforward to use. +However, DriverManager needs to be able to locate Driver subclasses, and +the JVM doesn't permit class enumeration at runtime.

+

In the original JDBC release, Driver subclasses were expected to register +themselves on load, similar to

+
public class ExampleDriver extends Driver {
+    static {
+        DriverManager.registerDriver(ExampleDriver.class);
+    }
+}
+
+

Obviously, applications can force drivers to load using +Class.forName(driverName), but this hasn't ever been the only way to do it. +DriverManager also provides a mechanism to load a set of named classes at +startup, +via the jdbc.drivers system property.

+

JDBC 4 Fixed That

+

JDBC 4, which came out with Java 6 in the Year of our Lord Two Thousand and +Six, also loads drivers using the service +provider +system, which requires no intervention at all from deployers or application +developers.

+

You don't need to write any code to load a JDBC 4 driver.

+

What's The Harm?

+

It's harmless in the immediate sense: forcing a driver to load immediately +before JDBC would load it itself has no additional side effects. However, it's +a pretty clear indicator that you've copied someone else's code without +thoroughly understanding what it does, which is a bad habit.

+

But What About My Database?

+

You don't need to worry about it. All of the following drivers support JDBC +4-style automatic discovery:

+ +
+ + + +
+
+ + +comments powered by Disqus +
+ + + + + +
+ + \ No newline at end of file -- cgit v1.2.3