Reprint: http://blog.csdn.net/iloveyin/article/details/7965183
1, the class loading mode is different
When executing class.forname ("A.class.name"), the JVM will find the corresponding class in classapth and load it, and the JVM will execute the static code snippet for that class. When using the Newinstance () method, it is necessary to ensure that the class is loaded and connected, which can be done through the static method of Class forname ().
When using the keyword new to create a class, this class can not be loaded and generally does not require the class to be set in classpath, but may need to be loaded by Classlaoder.
2. The constructor method called is different
The New keyword can call any constructor method.
Newinstance () can only invoke the parameterless constructor method.
3. Different implementation efficiency
The new keyword is strongly typed and relatively high-efficiency.
Newinstance () is a weakly-typed, relatively low-efficiency.
Now that you can create objects with the New keyword using newinstance (), why would you use Newinstance () to create objects?
Suppose you define an interface Door, and start with a wooden door, defined as a class Woodendoor, in the program it is necessary to write Door Door = new Woodendoor (). Suppose later living conditions improve, for automatic door, define a class Autodoor, then the program will be rewritten as Door Door = new Autodoor (). Although just change the identifier, if such statements are particularly large, the changes are quite big. So there is the factory model, all door instances are provided by doorfactory, when a different door, only need to change the factory production mode, or to change a bit of code.
If you use Newinstance (), you can change to a different door without changing the code. The specific method is to put the class name of the door implementation class into the configuration file and generate the instance by Newinstance (). This way, when you change another door, just change the configuration file. The sample code is as follows:
String ClassName = The class name of the specific implementation class that reads the door from the configuration file;
Door Door = (Door) class.forname (className). newinstance ();
With the method of dependency injection, the scalability and scalability of software are improved.
The difference between the new keyword and the newinstance () method