(go) deep understanding of Java object creation process

Source: Internet
Author: User
Tags reflection serialization stub

Reference Source: http://blog.csdn.net/justloveyou_/article/details/72466416

Summary:

In Java, an object must be properly initialized before it can be used, as defined by the Java specification. When instantiating an object, the JVM first checks that the correlation type has been loaded and initialized, and if not, the JVM immediately loads and invokes the class constructor to complete the initialization of the class. After the class is initialized or initialized, the class is instantiated based on the specific circumstances. This article attempts to provide a detailed and in-depth description of the JVM's execution of class initialization and instantiation in order to clearly dissect the creation of a Java object from the perspective of a Java virtual machine.

Copyright Notice:

This article original nerd Rico
Author Blog address: http://blog.csdn.net/justloveyou_/

Friendly tips:

The process of creating a Java object often involves two stages of class initialization and class instantiation . The sister article of this article, "Overview of the loading mechanism of JVM class: Loading time and loading process" mainly introduces the initialization time and initialization process of class, and further expounds the real process of the creation of a Java object on this basis.

First, Java object creation time

We know that an object must be properly instantiated before it can be used. In Java code, there are many behaviors that can cause an object to be created, and the most intuitive is to use the New keyword to invoke the constructor of a class to explicitly create an object, which is known in the Java specification as an object creation that is caused by an execution class instance creation expression . In addition, we can also use the reflection mechanism (the class's Newinstance method, the Newinstance method using the constructor class), the use of the Clone method, the use of deserialization, and other ways to create the object. The following is a brief description of the author:

1). Create an object using the New keyword

This is our most common and simplest way to create objects, and in this way we can invoke arbitrary constructors (without arguments and arguments) to create objects. Like what:

Student Student = new Student ();

2). Using the class Newinstance method (reflection mechanism)

We can also use the Newinstance method of the class class to create an object through the reflection mechanism of Java, in fact, the Newinstance method calls the parameterless constructor to create the object, such as:

   Student Student2 = (Student) class.forname ("Student class fully qualified name"). newinstance (); Or: Student stu = Student.class.newInstance ();

3). Using the Newinstance method of the constructor class (reflection mechanism)

There is also a newinstance method in the Java.lang.relect.Constructor class that can create objects, much like the Newinstance method in class classes, but in contrast, the Newinstance method of the constructor class is more powerful, We can call arguments and private constructors through this newinstance method, such as:

public class Student {    private int id;    Public Student (Integer ID) {        this.id = ID;    }    public static void Main (string[] args) throws Exception {        constructor<student> Constructor = Student.class                . GetConstructor (integer.class);        Student stu3 = constructor.newinstance (123);}    }

These two ways of using the Newinstance method create objects using the reflection mechanism of Java, in fact the Newinstance method of class is also constructor Newinstance method.

4). Create an object using the Clone method

Whenever we invoke the Clone method of an object, the JVM will help us create a new, identical object, and it is particularly necessary to note that no constructors are called in the process of creating an object with the Clone method. on how to use the Clone method and the shallow clone/deep clone mechanism, the author has made a detailed description in the blog post "Java String review (Next article)". Simply put, to use the Clone method, we must first implement the Cloneable interface and implement its definition of the Clone method, which is also the application of prototype mode. Like what:

public class Student implements cloneable{    private int id;    Public Student (Integer ID) {        this.id = ID;    }    @Override    protected Object Clone () throws Clonenotsupportedexception {        //TODO auto-generated method stub        return Super.clone ();    }    public static void Main (string[] args) throws Exception {        constructor<student> Constructor = student.class< C11/>.getconstructor (integer.class);        Student stu3 = constructor.newinstance (123);        Student Stu4 = (Student) stu3.clone ();}    }

5). Create an object using the (reverse) serialization mechanism

When we deserialize an object, the JVM creates a separate object for us, during which the JVM does not invoke any constructors. In order to deserialize an object, we need to have our class implement the Serializable interface, for example:

public class Student implements Cloneable, Serializable {    private int id;    Public Student (Integer ID) {        this.id = ID;    }    @Override public    String toString () {        return "Student [id=" + ID + "]";    }    public static void Main (string[] args) throws Exception {        constructor<student> Constructor = student.class
   .getconstructor (integer.class);        Student stu3 = constructor.newinstance (123);        Write Object        objectoutputstream output = new ObjectOutputStream (                new FileOutputStream ("Student.bin"));        Output.writeobject (STU3);        Output.close ();        Read Object        objectinputstream input = new ObjectInputStream (New FileInputStream (                "Student.bin"));        Student Stu5 = (Student) input.readobject ();        System.out.println (STU5);    }}

6). Full instance

public class Student implements Cloneable, Serializable {private int id;    Public Student () {} public Student (Integer id) {this.id = ID;        } @Override protected Object clone () throws Clonenotsupportedexception {//TODO auto-generated method stub    return Super.clone ();    } @Override Public String toString () {return "Student [id=" + ID + "]";        public static void Main (string[] args) throws Exception {System.out.println ("create object using the New keyword:");        Student stu1 = new Student (123);        System.out.println (STU1);        System.out.println ("\ n---------------------------\ n");        System.out.println ("Using the class Newinstance method to create an object:");    Student STU2 = Student.class.newInstance ();        The corresponding class must have an parameterless construction method, and only this one is created System.out.println (STU2);        System.out.println ("\ n---------------------------\ n");        System.out.println ("Create object using the Newinstance method of the constructor class:"); constructor<student> Constructor = student.clGetConstructor (Integer.class);           Call the parameter construction method Student STU3 = Constructor.newinstance (123);        System.out.println (STU3);        System.out.println ("\ n---------------------------\ n");        System.out.println ("Create object using Clone method:");        Student Stu4 = (Student) stu3.clone ();        System.out.println (STU4);        System.out.println ("\ n---------------------------\ n");        System.out.println ("Use (reverse) serialization mechanism to create objects:");        Write Object ObjectOutputStream output = new ObjectOutputStream (New FileOutputStream ("Student.bin"));        Output.writeobject (STU4);        Output.close ();        Read object ObjectInputStream input = new ObjectInputStream (New FileInputStream ("Student.bin"));        Student Stu5 = (Student) input.readobject ();    System.out.println (STU5); }}/* Output: Creating an object with the New keyword: Student [id=123]---------------------------using the newinstance side of class Create object by: Student [Id=0]---------------------------create an object using the Newinstance method of the constructor class: Student [id=123]------------------------  ---Create an object using the Clone method: Student [id=123]---------------------------Create an object using the (inverse) serialization mechanism: Student [id=123]*///:~

From the Java Virtual machine level, in addition to using the New keyword to create objects, all other ways to create objects directly by converting to invokevirtual directives.

(go) deep understanding of Java object creation process

Related Article

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.