Question : How does the following code works?
Answer: A half-baked answer would be that Class.forName() loads the database driver class some.database.Driver, and DriverManager.getConnection() returns the appropriate Connection instance based on the 'connection_url' provided. Let's figure out what actually happens. The Class.forName() method is responsible of loading the class some.database.Driver. We know that right after loading a class, it's static initializers are executed. The static intializer within some.database.Driver would look something like:
The Driver class tries to register it's own instance with the DriverManager. Now when we call DriverManager.getConnection(), it iterates through all the drivers registered with it and checks the appropriate driver for the 'connection_url'. If you examine the code in the class you would find a method getDriver() that does this.
As you can observe, the acceptsURL() method is called for each registered drivers and the first driver that belives it could connect to the specified database is returned. |