class.forName () Detailed

Class.forName action () method:

Its role is specified by the parameters of the class name in the string to search for and load the appropriate class if the class is already loaded over the byte code, an object instance is returned on behalf of the Class bytecode, otherwise, by class load commission's mechanism to search and load the class if all the class loader can not load into the class, then throws ClassNotFoundException. After loading the byte code Class, then Class newInstance method can be used to create the byte code class of the object instance.

class.forName(xxx.xx.x)返回的是一个类
任何class都要装载在虚拟机上才能运行,class.forName(xxx
的作用就是将类装载到虚拟机上。
A a = (A)Class.forName("pacage.A").newInstance();
和
A a = new A();
都是在实例化类A,但是他们创建对象的方式不一样,前者使用类加载的机制,
后者是创建一个类,前者创建类时,类已经被加载了,后者没有加载。

newInstance () method is called to initialize the new object with default constructor (no argument constructor).

Why use class.forname ()

Sometimes we program all the specific class names used can not be determined at design time (ie development), can be determined only when the program is running, this time you need to use Class.forName to dynamically load the class, the class name is usually in profile configuration. Java is often used in the factory mode newInstance () method to create the object, for example:
class C = the Class.forName ( "Example");
Factory = (ExampleInterface) c.newInstance ();

其中ExampleInterface是Example的接口,可以写成如下形式: 
String className = "Example"; 
class c = Class.forName(className); 
factory = (ExampleInterface)c.newInstance();

进一步可以写成如下形式: 
String className = readfromXMlConfig;//从xml 配置文件中获得字符串 
class c = Class.forName(className); 
factory = (ExampleInterface)c.newInstance();

上面代码已经不存在Example的类名称,它的优点是,无论Example类怎么变化,上述代码不变,甚至可以更换Example的兄弟类Example2 , Example3 , Example4……,
只要他们继承ExampleInterface就可以。

new keywords and newInstance difference:

  1. From the JVM's point of view, we use keywords to create a new class, this class can not be loaded. But using newInstance () method when it is necessary to ensure that:
    1, this class has been loaded; 2, this class has been connected. The two steps above is the Class static methods forName () completed, this static method calls start class loader that loads the loader java API's.

Summary:

  1.  jvm在装载类时会执行类的静态代码段,要记住静态代码是和class绑定的,class装载成功就表示执行了你的静态代码了,而且以后不会再执行这段静态代码了。
    
  2.  Class.forName(xxx.xx.xx)的作用是要求JVM查找并加载指定的类,也就是说JVM会执行该类的静态代码段。
    
  3.  动态加载和创建Class 对象,比如想根据用户输入的字符串来创建对象
    
    String str = 用户输入的字符串  
    
    Class t = Class.forName(str);  
    
    t.newInstance(); 
    

参考文献:https://blog.csdn.net/liletian2104/article/details/34415143
Published 50 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43668119/article/details/104539533