1. Class.forName
Class t = null;
t = Class.forName (m_simplclassname);
Icx_net bobj = (icx_net) t.getconstructor (null). newinstance (NULL);
2. LoadClass
Filterclass= Thread.CurrentThread (). Getcontextclassloader (). LoadClass (ClassName);
Filter = (filter) filterclass.newinstance ();
The difference simply says:
function, just use forname is the complete class loading initialization process, after calling Forname, the corresponding class of static{} block will be executed immediately
The LoadClass call does not execute immediately, but is executed after the newinstance
The following content is reproduced:
Class loading is divided into three phases, loading,linking and initializing, defined in the Java Language specification 12.2,12.3 and 12.4 respectively.
Class.forName (ClassName) is actually called Class.forName (ClassName, True, This.getclass (). getClassLoader ()). Note that the second parameter refers to whether the class must be initialized after being loading.
Classloader.loadclass (className) actually calls Classloader.loadclass (name, false), and the second argument indicates whether the class is link.
The difference is out. Class.forName (ClassName) loaded class has been initialized, and Classloader.loadclass (ClassName) loaded class is not yet link.
In general, the two methods have the same effect, and can load class. However, if the program relies on whether class is initialized, it must use Class.forName (name).
For example, in JDBC programming, this usage is often seen, Class.forName ("Com.mysql.jdbc.Driver"), if replaced by GetClass (). getClassLoader (). LoadClass (" Com.mysql.jdbc.Driver "), No.
Why, then? Open Com.mysql.jdbc.Driver's source code to see,
//
Register ourselves with the DriverManager
//
static {
try {
Java.sql.DriverManager.registerDriver (New Driver ());
catch (SQLException E) {
throw new RuntimeException ("Can ' t Register driver!");
}
}
Originally, driver in the static block will register themselves to Java.sql.DriverManager. And the static block is executed in the initialization of class. So this place can only use Class.forName (ClassName).