Creating objects for five different methods in Java _java

Source: Internet
Author: User

Objective

As a Java developer, we create a large number of objects every day, but we always use management-dependent systems such as the spring framework to create these objects. There are other ways to create objects, and I'll explain them in more detail in the following articles.

1. Use the New keyword

This is the most common method of creating objects, and is also very simple. By using this method we can invoke any constructor that we need to invoke.

Employee EMP1 = new Employee ();
0:new      #19     //class Org/programming/mitra/exercises/employee
 3:dup
 4:invokespecial #21     // Method Org/programming/mitra/exercises/employee. "":() V

2. The Newinstance method using class classes

We can also use the Newinstance method of class classes to create objects. This newinstance method calls the parameterless constructor to create the object.

We can create an object by Newinstance () in the following ways:

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

Similar to the method used with class classes newInstance , java.lang.reflect.Constructor there is a function method in the class that can be used to create the object newInstance() . By using this newInstance method we can also invoke parameterized constructors and private constructors.

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 newInstance() methods are considered to be the reflection means of creating objects. In fact, the method of the inner class newInstance() uses the method of the constructor class newInstance() . This is why the latter is preferred and uses different frameworks such as Spring, Hibernate, Struts .

4. Using the Clone method

In fact whenever we call clone a method, the Java virtual machine creates a new object for us and copies the contents of the previous object into the new object. Creating an object using a clone method does not call any constructors.

In order to use the method in the object clone() , we need to implement the clone type and define the Clone method.

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

5. Using deserialization

Whenever we serialize and deserialize an object, the Java virtual machine creates a separate object for us. In deserialization, the Java Virtual machine does not use any constructors to create objects.

Serializing an object requires that we implement a serializable interface in the class.

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Data.obj"));
Employee EMP5 = (employee) in.readobject ();
261:invokevirtual #118  //Method Java/io/objectinputstream.readobject: () Ljava/lang/object;

As we see in the byte code fragment above, the invokespecial other 4 methods are called and converted to. Except that the first one is converted to a new function and one instruction invokevirtual .

Example

Let's take a look at the classes that are ready to create objects Employee :

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 ObjectClone () {Object obj = null;
    try {obj = Super.clone ();
    catch (Clonenotsupportedexception e) {e.printstacktrace ();
  return obj; }
}

In the following Java program, we create Employee objects in 5 different 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 the Class class ' s Newinstance () method Employee EMP2 = (employee) class.forname ("Org.programming.mitra.exercis Es.
    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.getConst
    Ructor ();
    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 FileOutputStream (
    "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 ()); }
}

This program outputs the following results:

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

The above is about 5 different ways to create Java objects, and I want to help you learn java. And thank you for your support for the cloud-dwelling community.

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.