5 ways to create objects in Java the difference between the &&new keyword and the newinstance () method

Source: Internet
Author: User

Reprint: http://www.kuqin.com/shuoit/20160719/352659.html

Use the simplest description to differentiate between the new keyword and the newinstance () method :
Newinstance: Weak type. Low efficiency. Only parameterless constructs can be called.
NEW: Strongly typed. relatively efficient. Can invoke any public construct.

Newinstance () is a method, and new is a keyword, and second, the use of newinstance () under class is limited, because it generates objects that can only invoke parameterless constructors, and the use of the new keyword to generate objects does not have this limitation.
Class.forName ("") returns the class
Class.forName (""). Newinstance () returns an object

As Java developers, we create a lot of objects every day, but we often use dependency management systems like spring to create objects. However, there are many ways to create objects, which we will learn from this article.

There are 5 ways to create objects in Java, with examples of them and their bytecode:

Use the New keyword }→ called the constructor
Using the class Newinstance method }→ called the constructor
Using the Newinstance method of the constructor class }→ called the constructor
Using the Clone method }→ no constructor is called
Using deserialization }→ no constructor is called

If you run the program at the end, you will find that method 4,5 creates the object with the constructor, and the method does not call the constructor.

1. Use the New keyword

This is the most common and simplest way to create objects. In this way, we can call any constructor (with no arguments and with parameters).

Employee EMP1 = new Employee ();
0:new           #19          //class org/programming/mitra/exercises/employee3:dup4:invokespecial #21          //Method org/ Programming/mitra/exercises/employee. "":() V
2. Using the class Newinstance method

We can also use the class class's Newinstance method to create an object. This newinstance method calls the parameterless constructor to create the object.

We can create an object by calling the Newinstance method in the following way:

Employee EMP2 = (employee) class.forname ("Org.programming.mitra.exercises.Employee"). newinstance ();

Or:

Employee emp2 = Employee.class.newInstance ();

 

51:invokevirtual    #70    //Method java/lang/class.newinstance: () Ljava/lang/object;

 

3. Using the Newinstance method of the constructor class

Like the Newinstance method of class, there is also a newinstance method in the Java.lang.reflect.Constructor class that can create objects. We can call the parameterized and private constructors through this newinstance method.

constructor<employee> Constructor = Employee.class.getConstructor (); Employee Emp3 = Constructor.newinstance ();
111:invokevirtual  #80  //Method java/lang/reflect/constructor.newinstance: ([Ljava/lang/object;) Ljava/ Lang/object;

These two newinstance methods are what we call reflection. In fact, class's Newinstance method internally calls constructor's Newinstance method. This is also why many frameworks, such as spring, Hibernate, struts, etc. use the latter.

4. Using the Clone method

Whenever we invoke the Clone method of an object, the JVM creates a new object that copies the contents of the preceding object in its entirety. Creating an object with the Clone method does not call any constructors.

To use the Clone method, we need to implement the Cloneable interface first and implement its definition of the Clone method.

Employee Emp4 = (employee) emp3.clone ();
162:invokevirtual #87  //Method org/programming/mitra/exercises/employee.clone () Ljava/lang/object;
5. Using deserialization

When we serialize and deserialize an object, the JVM creates a separate object for us. When deserializing, the JVM creates an object and does not call any constructors.
In order to deserialize an object, we need to have our class implement the Serializable interface

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Data.obj")); Employee EMP5 = (employee) in.readobject ();
261:invokevirtual  #118   //Method Java/io/objectinputstream.readobject: () Ljava/lang/object;
We can see from the above bytecode fragment that in addition to the 1th method, the other 4 methods are all transformed into invokevirtual (the direct method of creating the object), the first method is converted to two calls, and the new and Invokespecial (constructor call).
Example

Let's take a look at creating an object for the following employee class:

Class Employee implements Cloneable, Serializable {private static final long serialversionuid = 1L;    private String name;    Public Employee () {System.out.println ("Employee Constructor called ...");    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;        } @Override public int hashcode () {final int prime = 31;        int result = 1;        result = Prime * result + ((name = = null)? 0:name.hashcode ());    return result;        } @Override public boolean equals (Object obj) {if (this = = obj) return true;        if (obj = = null) return false;        if (getclass () = Obj.getclass ()) return false;        Employee other = (employee) obj;        if (name = = null) {if (other.name! = null) return false;        } else if (!name.equals (Other.name)) return false;    return true; } @Override Public String ToString () {return "Employee [name=" + name + "]";        } @Override Public Object clone () {object obj = null;        try {obj = Super.clone ();        } catch (Clonenotsupportedexception e) {e.printstacktrace ();    } return obj; }}

In the following Java program, we will create the employee object in 5 ways.

public class Objectcreation {public static void main (String ... args) throws Exception {//by using new keyword        Employee EMP1 = new Employee ();        Emp1.setname ("Naresh");        System.out.println (Emp1 + ", Hashcode:" + emp1.hashcode ()); By using Class class ' s Newinstance () method Employee EMP2 = (employee) class.forname ("Org.programming.mitra.exer Cises.        Employee "). newinstance ();        Or we can simply do this//Employee EMP2 = Employee.class.newInstance ();        Emp2.setname ("Rishi");        System.out.println (EMP2 + ", Hashcode:" + emp2.hashcode ()); By using Constructor class ' s newinstance () method constructor<employee> Constructor = Employee.class.getCo        Nstructor ();        Employee Emp3 = Constructor.newinstance ();        Emp3.setname ("Yogesh");        System.out.println (Emp3 + ", Hashcode:" + emp3.hashcode ()); By using Clone () method Employee Emp4 = (employEE) emp3.clone ();        Emp4.setname ("Atul");        System.out.println (Emp4 + ", Hashcode:" + emp4.hashcode ()); By using deserialization//serialization ObjectOutputStream out = new ObjectOutputStream (New fileoutputs        Tream ("Data.obj"));        Out.writeobject (Emp4);        Out.close ();        Deserialization ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Data.obj"));        Employee EMP5 = (employee) in.readobject ();        In.close ();        Emp5.setname ("Akash");    System.out.println (Emp5 + ", Hashcode:" + emp5.hashcode ()); }}

The program will output:

Employee Constructor called ... Employee [Name=naresh], hashcode: -1968815046employee Constructor called ... Employee [Name=rishi], Hashcode:78970652employee Constructor called ... Employee [Name=yogesh], hashcode: -1641292792employee [Name=atul], Hashcode:2051657employee [Name=akash], hashcode:63 313419

  


 

5 ways to create objects in Java the difference between the &&new keyword and the newinstance () method

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.