When initializing a class to generate an instance, what is the difference between newinstance () and new?
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;//Gets the string Class C =class.forname (className) from the XML configuration file; 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 an inevitable choice for the implementation of IOC, reflection, interface programming and dependency inversion, and new can only be instantiated for specific classes, not suitable for interface programming.
Inside is an object constructed from the default constructor of this class, and if no default constructor is thrown, Instantiationexception is thrown if there is no permission to access the default constructor illegalaccessexception
Newinstance () and new