Five ways to create objects in Java

 3 minutes to read

Five ways to create objects in Java

This article will introduce five ways to create a Java object:

  • use the new keyword
  • use Class.newInstance
  • use Constructor.newInstance
  • use clone method
  • use deserialization

Create an object Student

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student implements Cloneable, Serializable {

    @Override
    public Student clone() throws CloneNotSupportedException {
        return (Student) super.clone();
    }

    private String name;
    private int age;
}
1. Created by the new keyword

Arbitrary constructors (parameterless and parameterized) can be called in this way

Student student = Student.builder().name("john").age(18).build();
log.info("get student>>>" + student);
Student student1=new Student();
student1.setAge(18);
student1.setName("john1");
log.info("get student>>>" + student1);
2.Class.newInstance

The newInstance of the Class class uses the public no-argument constructor of the class. Therefore, the premise of using this method to create an object must have a public no-argument constructor. You can also use Class.forName() to dynamically obtain the Class object of a class

try {
    Student student2 = Student.class.newInstance();
    student2.setName("john2");
    student2.setAge(18);
    log.info("get student2>>>" + student2);
    Class<?> clazz= Class.forName("com.example.demo.entity.Student");
    Student student3= (Student) clazz.newInstance();
    student3.setName("Hello");
    student3.setAge(19);
    log.info("get student3>>>" + student3);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
    e.printStackTrace();
}
3. Construct an object (reflection)

There is a newInstance method in the java.lang.reflect.Constructor class to create objects, Both parameterized (no longer has to be no-argument) and private constructors (no longer have to be public) can be called through this newInstance method.

try {
    Constructor<Student> constructor = Student.class.getConstructor();
    Student student4 = constructor.newInstance();
    student4.setAge(18);
    student4.setName("john");
    log.info("get student4>>>" + student4);

    Constructor<Student> constructor1 = Student.class.getConstructor(String.class, int.class);
    Student student5 = constructor1.newInstance("smith", 19);
    log.info("get student5>>>" + student5);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
    e.printStackTrace();
}
4. Clone an object

Whenever we call the clone method of an object, the JVM will create a new object and copy all the contents of the previous object into it. Creating an object with the clone method does not call any constructors. To use the clone method, we must first implement the Cloneable interface and override the clone method of Object, because this method of Object is protected. If it is not overridden, it cannot be called externally.

try {
    Student student6=student.clone();
    log.info("get student6>>>" + student6);
    log.info(String.valueOf(student==student6));
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}
5. Deserialization

When we serialize and deserialize an object, the JVM creates a separate object. When deserializing, the JVM creates the object without calling any constructors. In order to deserialize an object, the Student class needs to implement the Serializable interface.

try {
    ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("data.obj"));
    objectOutputStream.writeObject(new Student("john",19));
    objectOutputStream.close();

    ObjectInputStream inputStream=new ObjectInputStream(new FileInputStream("data.obj"));
    Student student7= (Student) inputStream.readObject();
    inputStream.close();
    log.info("get student7>>>" + student7);
} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
}
About the difference between the two newInstance methods?

The Class class is located in the lang package of java, and the Constructor is part of the java reflection mechanism

The newInstance of the Class class can only trigger the constructor without parameters to create an object, while the newInstance of the Constructor class can trigger the constructor with parameters or any parameters to create the object.

The newInstance of the Class class requires its constructor to be public or visible to the calling method, while the newInstance of the Constructor class can call the private constructor to create an object in a specific environment.

The newInstance of the Class class throws the exception of the class constructor, and the newInstance of the Constructor class wraps an InvocationTargetException exception.

The Class class essentially calls the parameterless newInstance method in the reflection package Constructor, catches the InvocationTargetException, and throws the exception of the constructor itself.