coolness

Thomas Reilly treilly@livesoftware.com
Fri Mar 12 16:30:00 GMT 1999


Tom Tromey <tromey@cygnus.com> writes:
> When you write this, do you mean that it is a common idiom to pass a
> constant string to Class.forName()? (I'm afraid most of the Java code
> I've read is code written here.)

Very common. Servlets and JDBC drivers are the best examples.
For JDBC dynamic loading of a Java class is absolutely necessary. The
idea is that you can write a Java program that accesses a SQL database
without specifying anything about the database beforehand.
So my Java app would have properties file that specified the the db
type and locale like so:
db_driver=postgresql.Driver
db_location=jdbc:postgresql://urizen:3094/myDataBase
My Java app would then read the properties file and do something like:
	String db_driver = props.getProperty("db_driver");
	Class.forName(db_driver);
Then I could pass the db url (stored in the db_location property) to
the JDBC DriverManager and it would know how to connect to it (by
using the postgresql.Driver class). This is because the
Class.forName() loads the postgresql.Driver class which has a static
block that registers itself with the JDBC DriverManager.
That brings up another point. Does gcj handle static initializer
blocks?
The power of this factory model comes from the fact that this Java app
could be moved to a different machine running a different database and
it would work automatically after changing the properties file
appropriately.
Servlets are almost the same except what gets passed to Class.forName
is created from a URL. So say I hit a servlet aware web server with a
URL like so:
http://host.com/servlets/MyServlet
The VM would have to do a Class.forName("MyServlet") if it hadn't
already.
--
Tom Reilly
Live Software, Inc
http://www.livesoftware.com


More information about the Java mailing list

AltStyle によって変換されたページ (->オリジナル) /