When initializing a class, generating an instance, what is the difference between newinstance () and new.
The difference between using newinstance and new is that the object is created differently, using the class loading mechanism, and why there are two ways of creating objects. This is going to be explained in terms of scalable, scalable, reusable software.
Factory patterns in Java often use 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 this, you may understand:
String className = "A"; Class C = class.forname (className); factory = (Ainterface) c.newinstance ();
Further, if you write below, you may understand:
String className = readfromxmlconfig;//from 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 a class changes, the above code is unchanged, can even replace a brother Class B, C, D .... Wait, as long as they inherit ainterface can.
From the JVM's point of view, when we use new, the class to be new can be loaded without loading;
However, when using newinstance, you must ensure that: 1, this class has been loaded, 2, this class has been connected. The static method Forname () method of class, which completes the above two steps, calls the Startup class loader (the one that loads the Java API).
With the understanding on the JVM above, we can say that newinstance actually breaks the new way into two steps, that is, to call the class's Load method first to load a class and then instantiate it.
The benefits of this step-by-step are obvious. We can get more flexibility when calling the static Load method of class forname, which gives us the means to decouple.
[Add:]
Newinstance: Weak type. Low efficiency. Only parameterless constructs can be invoked.
NEW: Strongly typed. relatively efficient. Can invoke any public construct.