Article From:https://www.cnblogs.com/didiaoxiong/p/9127665.html

Java5 ways of creating objects

 

As Java developers, we create many objects every day, but we usually use dependency management systems, such as Spring, to create objects. However, there are many ways to create objects. We will learn from this article.

JavaThere are 5 ways to create objects. Here are some examples of them and their bytecode.

Using the new keyword} → A constructor is called
Using the newInstance method of the Class class} → A constructor is called
Using the newInstance method of the Constructor class} → A constructor is called
Using the clone method} → No constructor is called
Use anti serialization} → No constructor is called

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

1.Using the new keyword

This is the most common and simplest way to create objects. In this way, we can call any constructor (without parameter and parameter).

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.Using the newInstance method of the Class class

We can also create objects using the newInstance method of the Class class. This newInstance method calls the constructor without arguments to create objects.

We can call the newInstance method to create objects in the following way:

Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance();
perhapsEmployee 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 newInstance method of Class class, there is also a newInstance method in java.lang.reflect.Constructor class to create objects. We can go through this newInstance partyThe method calls a parameter and a private constructor.

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, the newInstance method of Class calls the newInstance method of Constructor internally. This is also a number of frameworks, such as Spring and HibernThe reasons for the use of the latter, such as ate, Struts and so on. To understand the difference between the two newInstance methods, please look at this Creating objects through Reflection in Java with ExampLe.

4.Using the clone method

Whenever we call an object’s clone method, JVM creates a new object that copies all the contents of the preceding object. Creating objects with the clone method does not call any constructors.

To use the clone method, we need to implement the Cloneable interface first and implement the clone method that we define.

Employee emp4 = (Employee) emp3.clone();
162: invokevirtual #87  // Method org/programming/mitra/exercises/Employee.clone ()Ljava/lang/Object;

5.Use anti serialization

When we serialize and serialize an object, JVM will create a separate object for us. When anti serialization, JVM creates objects and does not call any constructors.
In order to serialize an object, we need to enable our class to 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 bytecode clip above that, in addition to first methods, the other 4 methods are all transformed into invokevirtual (the direct method of creating objects), the first method is converted to two calls, new and invokespecial (constructor call).

Example

Let’s take a look at creating objects for the following Employee class:

Copy code
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;
    }
}
Copy code

In the following Java program, we will create Employee objects in 5 ways. You can find the code from GitHub.

Copy code
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.exercises.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.getConstructor();
        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());
    }
}
Copy code

The program will output:

Copy code
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
Copy code

 

Maybe when I am old, I write code too; for nothing else, just for hobbies.

Similar Posts:

Link of this Article: 5 ways to create objects in Java

Leave a Reply

Your email address will not be published. Required fields are marked *