This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

uncomfortable syntax  RSS feed

 
salvador rcn
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, in JDBC connection in order to connect it is written.........

question :
is it not peculiar to write Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); ?
look, it is written Class ...it should have been the name of some class. how can i use Class keyword itself ? even in the case of static method we have seen to use the name of the class and the method name.
so how this syntax works ? its not following any rule.
can anybody have any say on this ?
thanks
 
eammon bannon
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

so how this syntax works ? its not following any rule.
can anybody have any say on this ?

It is following a rule. How so? Well for a start its not a keyword (though class is). For the rest, go look at the JavaDocs for the final class java.lang.Class. That should make it clear.
 
salvador rcn
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
javadocs says " static Class forName(String className)
Returns the Class object associated with the class or interface with the given string name.... ".
but in the code no body is there to catch the returned value from Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); !!!
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right, the Class object is returned, but you don't need it for anything. What you do need is for the driver class to be loaded, and the static initializer of that class to be executed. The static init code in the driver class will register the driver with the DriverManager, so that when you try to open a connection to a database, the DriverManager has that driver class available for use.
So the convention is to execute forName() like this solely to get the side effect of having the driver class loaded.
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Salvador: I agree, it is peculiar.
But it is necessary.
One alternative would be

- not portable.
But this way, you may have the name of the driver defined in some text-file, for configuration, and some code:

If only portable - sql is used, the user may change the whole database (SqlServer->Oracle->Postgres) without recompiling anything - just editing the config-file.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!