1

Possible Duplicate:
What is difference between “Class.forName()” and “Class.forName().newInstance()”?

In my android apps to connect mysql server using jdbc connection. In that I want to know difference

`Class.forName("com.mysql.jdbc.Driver");` 

and

Class.forName("com.mysql.jdbc.Driver").newInstance(); 

and also how to set the timeout functions, when server is not connected?

4

1 回答 1

3

Class.forName() returns a Class object -- an object that represents a particular Java class.

newInstance() -- a method of java.lang.Class -- will use the no-argument constructor of the represented class to create an instance of that class.

For your question: (Reference from http://www.coderanch.com/t/385654/java/java/Difference-between-Class-forName-Class)

Class.forName() gets a reference to a Class, Class.forName().newInstance() tries to use the no-arg constructor for the Class to return a new instance. No surprises so far. Another common use for Class.forName() is to cause the Class to be loaded, since some types of Classes have side-effects from the loading process which is required for other purposes. JDBC is a large user of this process, since the Driver class is required to register itself with the DriverManager Class when it gets loaded.

In the deep dark days of Java, probably v1.1.8 but possibly up to Java 1.2, there was an issue that the default ClassLoader would not load a Class until it had an instance created. In these cases, JDBC code would fail if you used Class.forName() rather than Class.forName().newInstance().

While newInstance() would create an instance that got immediately thrown away, it was required to make Class.forName() work correctly. This work around is no longer required.

于 2012-07-17T07:03:55.087 回答