The difference between using newinstance and using new is that the object is created differently, the former is using the class loading mechanism, so why are there two ways to create objects? This is going to be explained in terms of scalable, extensible, reusable software. Factory mode in Java often uses Newinstance to create objects, so you can find specific answers from why you use Factory mode.
For example:
Class C = class.forname ("A");
factory = (ainterface) c.newinstance ();
where Ainterface is the interface of a, if you write the following, you may understand:
String className = "A";
Class C = class.forname (className);
factory = (ainterface) c.newinstance ();
further, if written below, you may understand:
String className = readfromxmlconfig;//getting a string from an XML configuration file
Class C = class.forname (className), factory = (ainterface) c.newinstance ();
The above code eliminates the Class A name, the advantage: No matter how the Class A changes, the above code is unchanged, can even replace A's brothers B, C, D ... etc., as long as they inherit the ainterface can.
from the JVM's point of view, when we use new, the new class can not be loaded;
however, when using newinstance, it is necessary to ensure that: 1, this class has been loaded, 2, this class has been connected. The forname () method, which completes the two steps above, is the static method of class, which invokes the startup ClassLoader (that is, the loader that loads JAVAAPI).
with the understanding on the JVM above, we can say that newinstance actually breaks the new approach into two steps, that is, first calling class's Load method to load a class 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 us with the means to decouple.
[Add:]
newinstance: Weak type. Low efficiency. Only parameterless constructs can be called.
NEW: Strongly typed. relatively efficient. Can invoke any public construct.
newinstance () is the inevitable choice to implement the IOC, reflection, dependency inversion and other technical methods, new can only realize the instantiation of specific classes, not suitable for interface programming. The class is built with the default constructor of the class, and if no default constructor is thrown, Instantiationexception is thrown if there is no permission to access the default constructor illegalaccessexception
Using Newinstance with new is the district