Write code see a newinstance () statement, not very understand it and new () of the difference, find some information, summarized here. Let's look at an example:
Package com.zz.bridge.impl;/** * Copyright June 16, 2015 * Created by TXXS * All right reserved */public class Classdemo {/** * Constructor */public Classdemo () {System.out.println ("classdemo!");} public static void Main (string[] args) throws Exception {/*** class.forname (String): Requires the JVM to find and load the class specified by the String * Returns the class specified by string string */class Clazz = Class.forName ("Com.zz.bridge.impl.ClassDemo"); System.out.println (clazz);/** * Clazz.newinstance () * The Returned class represents one instance and the new Classdemo () effect is the same. */classdemo Classdemo = (Classdemo) clazz.newinstance (); System.out.println (Classdemo);}}
Operation Result:
Class com.zz.bridge.impl.classdemoclassdemo! [Email protected]
Difference:
1, using newinstance can be decoupled. The premise of using newinstance is that the class is loaded and the class is connected, which is exactly what the static method of Class forname () is doing. Newinstance actually breaks the new approach into two steps, that is, to first call the class's Load method to load a category and instantiate it.
2, Newinstance: weak type. Low efficiency. Only parameterless constructs can be called. NEW: Strongly typed. relatively efficient. Can invoke any public construct.
3, Newinstance () is the implementation of the IOC, reflection, face interface programming and dependency inversion of the technical methods of the inevitable choice, new can only achieve the specific instantiation of the class, not suitable for interface programming.
4, newinstance () is generally used for dynamic load classes.
Class.forName (). newinstance () and the difference between objects obtained by new