Detailed explanation of the usage of Class.forName() in Java

http://blog.csdn.net/zhangxichao100/article/details/51168014

Class.forName() main function
Class.forName(xxx.xx.xx) returns a class,
The role of Class.forName(xxx.xx.xx) is to ask the JVM to find and load the specified class, which means that the JVM will execute the static code segment of the class.

Next, the usage of Class.forName() will be explained in detail by answering the following three questions.
1. When to use Class.forName()?
Given a string variable that represents the package name and class name of a class, how do you instantiate it? Your first thought must be new, but pay attention:
A a = (A)Class.forName("pacage.A").newInstance();
This is the same as your A a = new A();

Closer to home now.
Dynamically load and create Class objects, for example, when you want to create objects based on user-input strings:
String str = "user-input strings" ;
Class t = Class.forName(str);
t.newInstance();

When initializing a class and generating an instance, what is the main difference between the newInstance() method and the new keyword, except that one is a method and the other is a keyword? The difference between them is the way to create objects, the former is to use the class loading mechanism, the latter is to create a new class. So why are there two ways to create objects? This mainly considers software design ideas such as scalability, extensibility and reusability of software.

The factory pattern in Java often uses the newInstance() method to create objects, so you can find a specific answer from why you should use the factory pattern. For example:
class c = Class.forName("Example");
factory = (ExampleInterface)c.newInstance();

Among them, ExampleInterface is the interface of Example, which can be written in the following form:
String className = "Example";
class c = Class.forName(className);
factory = (ExampleInterface)c.newInstance();

It can be further written in the following form:
String className = readfromXMlConfig;//Get the string from the xml configuration file
class c = Class.forName(className);
factory = (ExampleInterface)c.newInstance();

The above code no longer has the class name of Example. Its advantage is that no matter how the Example class changes, the above code remains unchanged, and even the sibling classes Example2, Example3, Example4... of Example can be replaced, as long as they inherit ExampleInterface.

From the JVM's point of view,

我们使用关键字new创建一个类的时候,这个类可以没有被加载。但是使用newInstance()方法的时候,就必须保证:
1、这个类已经加载;
2、这个类已经连接了。
而完成上面两个步骤的正是Class的静态方法forName()所完成的,这个静态方法调用了启动类加载器,即加载 java API的那个加载器。

现在可以看出,newInstance()实际上是把new这个方式分解为两步,即首先调用Class加载方法加载某个类,然后实例化。 这样分步的好处是显而易见的。我们可以在调用class的静态加载方法forName时获得更好的灵活性,提供给了一种降耦的手段。

二.new 和Class.forName()有什么区别?
其实上面已经说到一些了,这里来做个总结:
首先,newInstance( )是一个方法,而new是一个关键字;
其次,Class下的newInstance()的使用有局限,因为它生成对象只能调用无参的构造函数,而使用 new关键字生成对象没有这个限制。
简言之:
newInstance(): 弱类型,低效率,只能调用无参构造。
new: 强类型,相对高效,能调用任何public构造。
Class.forName(“”)返回的是类。
Class.forName(“”).newInstance()返回的是object 。
三.为什么在加载数据库驱动包的时候有用的是Class.forName( ),却没有调用newInstance( )?
在Java开发特别是数据库开发中,经常会用到Class.forName( )这个方法。
通过查询Java Documentation我们会发现使用Class.forName( )静态方法的目的是为了动态加载类。
通常编码过程中,在加载完成后,一般还要调用Class下的newInstance( )静态方法来实例化对象以便操作。因此,单单使用Class.forName( )动态加载类是没有用的,其最终目的是为了实例化对象。

有数据库开发经验朋友会发现,为什么在我们加载数据库驱动包的时候有的却没有调用newInstance( )方法呢?
即有的jdbc连接数据库的写法里是Class.forName(xxx.xx.xx);而有一 些:Class.forName(xxx.xx.xx).newInstance(),为什么会有这两种写法呢?
刚才提到,Class.forName(“”);的作用是要求JVM查找并加载指定的类,首先要明白,java里面任何class都要装载在虚拟机上才能运行,而静态代码是和class绑定的,class装载成功就表示执行了你的静态代码了,而且以后不会再走这段静态代码了。
而我们前面也说了,Class.forName(xxx.xx.xx)的作用就是要求JVM查找并加载指定的类,如果在类中有静态初始化器的话,JVM必然会执行该类的静态代码段。
而在JDBC规范中明确要求这个Driver类必须向DriverManager注册自己,即任何一个JDBC Driver的 Driver类的代码都必须类似如下:
public class MyJDBCDriver implements Driver {
static {
DriverManager.registerDriver(new MyJDBCDriver());
}
}
既然在静态初始化器的中已经进行了注册,所以我们在使用JDBC时只需要Class.forName(XXX.XXX);就可以了。


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325465433&siteId=291194637