Database links and Class.forName () Usage details __ Database

Source: Internet
Author: User

Original Address http://blog.csdn.net/kaiwii/article/details/7405761

The main function
class.forname (xxx.xx.xx) returns a class
Class.forName (xxx.xx.xx) that requires the JVM to
find and load the specified class. In other words, the JVM executes the static code snippet for that class

Below, the use of class.forname () is explained in detail by answering the following three questions.
A. When to use Class.forName ().
Let's start with a warm-up and give you a string variable that represents the package name and class name of a class, and how you instantiate it. The first thing you think of is new, but be careful:
A A = (a) class.forname ("Pacage"). A "). newinstance ();
This is the same effect as you a A = new A ();

Now, let's do it.
dynamically loading and creating a class object, such as creating an object based on a string entered by the user, requires:
String str = "User-entered strings";
Class t = class.forname (str);
T.newinstance ();

When initializing a class and generating an instance, the Newinstance () method and the new keyword have the most important difference except that one is a method and one is a keyword. The difference is that the object is created in a different way, using the class-loading mechanism, which creates a new class. So why are there two ways of creating objects? This mainly considers software design ideas such as scalable, scalable and reusable software.

Factory patterns in Java often use the newinstance () method to create objects, so you can find specific answers from why you use Factory mode. For example:
Class C = Class.forName ("Example");
Factory = (exampleinterface) c.newinstance ();

Where Exampleinterface is the example interface, it can be written in the following form:
String className = "Example";
Class C = Class.forName (ClassName);
Factory = (exampleinterface) c.newinstance ();

Further can be written in the following form:
String className = readfromxmlconfig;//get strings from XML configuration file
Class C = Class.forName (ClassName);
Factory = (exampleinterface) c.newinstance ();

The above code already does not exist example class name, its advantage is, regardless of example class how change, the above code is invariable, can even replace example brothers class Example2, Example3, Example4 ..., As long as they inherit exampleinterface.

From the JVM's point of view, when we use the keyword new to create a class, this class can be not loaded. However, when using the Newinstance () method, you must ensure that:
1, this class has been loaded;
2, this class has been connected.
The static method forname (), which completes the two steps above, is done by calling the boot class loader, the loader that loads the Java API.

As you can see now, newinstance () actually breaks down the new method into two steps, which is to first call the class load method to load a class and then instantiate it. The benefits of this step-by-step are obvious. We can get more flexibility when calling the static Load method of class forname, and provide a means of decoupling.

What is the difference between

two. New and Class.forName ().
Actually, here's a summary:
First, newinstance () is a method, and new is a keyword;
second, the use of newinstance () under Class is limited, Because it generates objects that can only invoke parameterless constructors, there is no limit to using the New keyword to generate objects.
In short:
Newinstance (): weakly typed, inefficient, can only invoke parameterless constructs.
NEW: Strongly typed, relatively efficient, and can invoke any public construct. The
Class.forName ("") returns a class.
Class.forName (""). Newinstance () returns an object.
Three. Why it is class.forname () that is useful when loading the database driver package, but does not invoke newinstance ().
The Class.forName () method is often used in Java development, especially in database development.
by querying the Java documentation we find that the purpose of using the Class.forName () static method is to dynamically load the class.
Usually, after loading completes, the newinstance () static method under class is typically invoked to instantiate the object for manipulation. Therefore, it is no use simply to use Class.forName () to dynamically load classes, whose ultimate goal is to instantiate objects.

Have database development experience friends will find out why we did not call the Newinstance () method when we loaded the database driver package.
The JDBC Connection database is written in Class.forName (xxx.xx.xx), and there are some: Class.forName (xxx.xx.xx). newinstance (), why are these two ways of writing?
just mentioned, Class.forName (""), the role is to require the JVM to find and load the specified class, first of all to understand that any class in Java to be loaded on the virtual machine to run, and static code is bound to the class, Class load success means that you have executed your static code and will not go through this static code again.
and as we said earlier, the role of Class.forName (XXX.XX.XX) is to require the JVM to find and load the specified class, and if there is a static initializer in the class, the JVM will inevitably execute the static code snippet for that class. The
explicitly requires in the JDBC specification that the driver class must register itself with DriverManager, that is, the code for any driver class of the JDBC driver must resemble the following:
public class Myjdbcdriver Implements Driver {
Static {
Drivermanager.registerdriver (new Myjdbcdriver ());
}
}
Now that you have registered in the static initializer, we need only class.forname (xxx.xxx) when using JDBC;

The relevant English references are as follows:
we just want to load the driver to JVM only, but not need to user the instance of driver, so call
Clas S.forname (xxx.xx.xx) is enough, if your call Class.forName (xxx.xx.xx). newinstance (), the result would
same as calling Cl Ass.forname (xxx.xx.xx),
because Class.forName (xxx.xx.xx). newinstance () 'll load driver-I, and
then Create instance, but the instacne you'll never use in usual, so you need don't to
create it.

The first step: in the static code block, directly load the database driver
//load driver, not directly to the use of com.mysql.jdbc.Driver on the//
said, do not hard-code, his reason is here
// 
/ /Com.mysql.jdbc.Driver only represents the MySQL database driver
//So, if one day, our project the underlying database to migrate, such as the migration to Oracle
//or DB2, SQL Server
//Then, it must be laborious to find in the code, find the Hard-coded com.mysql.jdbc.Driver, and then change to
//other database driver class name
//So the regular item is not allowed to Hard-code, That's a high maintenance cost./// 
Usually, we are using a constant in a constant interface to represent a value
///And then when the value changes, just change the value 
of the constant in the constant interface. To try to make configurable
//That is, our database driver, further, and not just in the constant interface can be//the
best way, is placed in the external configuration file, with the code completely separated
//constant interface, It just contains the name of the key that corresponds to this value.

Class reprint of the time this static code has been loaded into the JVM, so there is no need to instance the

static {
   try {
      String driver = Configurationmanager.getproperty (constants.jdbc_driver);
      Class.forName (driver);
   } catch (Exception e) {
      e.printstacktrace ();  
   }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.