As Java developers, we create a large number of objects every day, but we always use management dependency systems (such as the Spring framework) to create these objects. In fact, there are other methods to create objects, which I will introduce in detail in the next article.
1. Use the new keyword
This is the most common method of creating objects, and it is also very simple. By using this method, we can call any constructor we need to call.
1 | Employee emp1 = new Employee(); |
1 2 3 | 0: new #19 // class org/programming/mitra/exercises/Employee 3: dup 4: invokespecial #21 // Method org/programming/mitra/exercises/Employee."":()V |
2. Use the newInstance method of class class
We can also use the newInstance() method of class class to create objects. This newInstance() method calls the parameterless constructor to create the object.
We can create objects through newInstance():
1 | Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance(); |
perhaps
1 | Employee emp2 = Employee.class.newInstance(); |
1 | 51: invokevirtual #70 // Method java/lang/Class.newInstance:()Ljava/lang/Object; |
3. Use newInstance method of constructor class
Similar to using the newInstance() method of the class class, the java.lang.reflect.Constructor class has a newInstance() function method that can be used to create objects. By using this newInstance() method, we can also call parameterized constructors and private constructors.
1 2 | Constructor<Employee> constructor = Employee.class.getConstructor(); Employee emp3 = constructor.newInstance(); |
1 | 111: invokevirtual #80 // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object; |
These newInstance() methods are considered reflection means for creating objects. In fact, the newInstance() method of the inner class uses the newInstance() method of the constructor class. This is why the latter is preferred and uses different frameworks, such as Spring, Hibernate, Struts, etc.
4. Use clone method
In fact, whenever we call the clone() 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 the clone() method does not call any constructors.
In order to use the clone() method in an object, we need to implement the clonable type and define the clone() method.
1 | Employee emp4 = (Employee) emp3.clone(); |
1 | 162: invokevirtual #87 // Method org/programming/mitra/exercises/Employee.clone ()Ljava/lang/Object; |
5. Use deserialization
Whenever we serialize and deserialize an object, the JAVA virtual machine will create a separate object for us. In deserialization, the JAVA virtual machine does not use any constructors to create objects.
Serializing an object requires us to implement a serializable interface in the class.
1 2 | ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj")); Employee emp5 = (Employee) in.readObject(); |
1 | 261: invokevirtual #118 // Method java/io/ObjectInputStream.readObject:()Ljava/lang/Object; |
As we can see in the byte code fragment above, except that the first method is converted to a new function and an invokespecial instruction, the other four methods are called and converted to invokevirtual.
Example
Let's take a look at the Employee class to create the object:
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 create an Employee object in five 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.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()); } }
The output of this program is as follows:
1 2 3 4 5 6 7 8 | 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 |