简体   繁体   中英

Java JAR (library) usage

I've used once a GSON library in Eclipse and it was very easy. Just added it as external library and in source file I've imported it and was able to use it just like any other class in Java. Example:

Gson gson = new Gson(); //and just use it

Recently I had to work with SQLIte database file, so I've downloaded JDBC driver library and added it in my Eclipse project. But I've noticed that there is kind of strange (at least for me) syntax for using it. I've imported java.sql.* but to be able to use its classes I had to do the following:

 Class.forName("org.sqlite.JDBC");

I know that the return value from this command is Class object (during runtime) but as you can see from the syntax it is never used.

Please explain whats going on there and why I can't just use SQL package classes without invoking Class.forName first.

It loads a class dynamically. What does Class.forname method do? is a good article about it and it also explains why database drivers needs it:

Let's see why you need Class.forName() to load a driver into memory. All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static an initializer only.

The MySQL JDBC Driver has a static initializer looks like this:

static {
    try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
    }
}

JVM executes the static block and the Driver registers itself with the DriverManager.

You need a database connection to manipulate the database. In order to create the connection to the database, the DriverManager class has to know which database driver you want to use. It does that by iterating over the array (internally a Vector) of drivers that have registered with it and calls the acceptsURL(url) method on each driver in the array, effectively asking the driver to tell it whether or not it can handle the JDBC URL.

Source - What does 'Class.forName("org.sqlite.JDBC");' do?

Basically it lets the JVM register which implementation of the java.sql.* libraries your code is using. This way you can rely on a standard interface without going through the hoops and hurdles that require implementation-level details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM