Class.forName (). newinstance () and the difference between objects obtained by new

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.