Class.forName () Usage explanation

Source: Internet
Author: User

 Class.forName () usage explanationTags: classjvmjdbc database Documentationjava2012-03-29 09:39 40414 People read Comments (8) favorite reports Classification:Java Archaeology (a)
The main function of Class.forName (XXX.XX.XX) is to return the function of a class Class.forName (xxx.xx.xx) that requires the JVM to find and load the specified class, which means that the JVM executes the static code snippet of the class

Below, we will explain the usage of class.forname () in detail by answering the following three questions.
A. When to use Class.forName ()?
Let's start with a warm-up, give you a string variable, which represents the package name and class name of a class, how do you instantiate it? Your first thought must be new, but be careful:
A A = (a) class.forname ("Pacage"). A "). newinstance ();
This is the same effect as you a = new A ().

Let's do it now.
dynamically loading and creating class objects, such as the need to create objects based on a string entered by the user:
String str = "User-entered string";
Class t = class.forname (str);
T.newinstance ();

When initializing a class, generating an instance, the Newinstance () method and the new keyword are the main differences except one method and one keyword. They differ in the way that objects are created, using the class-loading mechanism, which creates a new class. So why are there two ways to create objects? This mainly takes into account the software design ideas of scalability, extensibility and reusability.

Factory mode in Java often uses 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 interface of example, it can be written as follows:
String className = "Example";
Class C = Class.forName (ClassName);
Factory = (exampleinterface) c.newinstance ();

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

The above code no longer exists example class name, its advantage is that no matter how the example class changes, the above code is unchanged, can even replace example brothers Example2, Example3, Example4 ... As long as they inherit exampleinterface, they can.

From the JVM's point of view, when we use the keyword new to create a class, the class can not be loaded. However, when using the Newinstance () method, it is necessary to ensure that:
1, this class has been loaded;
2, this class has been connected.
The two steps above are done by the static method of Class forname (), which invokes the startup ClassLoader, the one that loads the Java API.

As can be seen now, newinstance () is actually breaking new into two steps, that is, calling the class load method to load a class first and then instantiating it. The benefits of this step are obvious. We can get better flexibility when invoking the static Load method of class forname, providing a means of decoupling.

What is the difference between

two. New and Class.forName ()?
In fact, some of the above has been said, here to make a summary:
First, newinstance () is a method, and new is a keyword;
Secondly, the use of newinstance () under Class is limited, Because it generates objects that can only call parameterless constructors, there is no limit to generating objects using the New keyword.
In short:
Newinstance (): weak type, inefficient, can only invoke parameterless constructs.
NEW: Strong type, relatively efficient, can invoke any public construct.
Class.forName ("") returns the class.
Class.forName (""). Newinstance () returns an object.
Three. Why is Class.forName () useful when loading a database driver package without calling newinstance ()? The
Class.forName () method is often used in Java development, especially in database development.
By querying Java documentation We will find that the purpose of using the Class.forName () static method is to dynamically load the class. The
is usually encoded in the process, and after the load is complete, you typically call the Newinstance () static method under class to instantiate the object for operation. Therefore, it is useless to use only class.forname () to dynamically load a class, and its ultimate purpose is to instantiate the object.

Experience with database development friends will find out why we didn't call the Newinstance () method when we loaded the database driver package. The
that is, the JDBC Connection database is written in Class.forName (xxx.xx.xx), and some: Class.forName (xxx.xx.xx). newinstance (), why do you have these two kinds of wording?
just mentioned, Class.forName (""), the role is to require the JVM to find and load the specified class, first of all, it is necessary to understand that any class in Java to be loaded on the virtual machine to run, and static code is bound to Class, The success of class loading indicates that you have executed your static code and will not go through this static code again.
and as we said earlier, Class.forName (xxx.xx.xx) has the function of requiring the JVM to find and load the specified class, and if there is a static initializer in the class, the JVM will necessarily execute the static code snippet for that class. The
and in the JDBC specification explicitly requires that the driver class must register itself with DriverManager, which means that the code of any JDBC driver driver class must resemble the following:
public class Myjdbcdriver Implements Driver {
Static {
Drivermanager.registerdriver (new Myjdbcdriver ());
}
}
Since it has been registered in the static initializer, we only need Class.forName (XXX.XXX) when using JDBC;

The relevant English references are as follows: We just want to load the driver to the JVM is only, and not need to user the instance of Driver,so call Class.forName ( XXX.XX.XX) is enough, if you call Class.forName (xxx.xx.xx). newinstance (), the result would same as calling Class.forName (xxx . xx.xx), because Class.forName (xxx.xx.xx). newinstance () would load driver First,and then create instance, but the Instacne y Ou'll never use in usual,so you need not to create it.

Class.forName () Usage explanation

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.