We all know how to create objects of any class. Simplest method to create object in Java is using new keyword. Let’s explore other methods to create object without new keyword in Java.
Table of contents Using Class.forName() and Class.newInstance() ClassLoader loadClass() Using Object.clone() Deserialization Using reflection
Note: In given examples, I am writing pseudo code only. For building complete fully working sample code, please read about related feature.
Create object using Class.newInstance()
Class ref = Class.forName("DemoClass"); DemoClass obj = (DemoClass) ref.newInstance();
Class.forName() loads the class in memory. To create an instance of this class, we need to use
Create object using class loader’s loadClass()
Just like above method, class loader’s
loadClass() method does the same thing. It creates a new instance of class using an existing instance of same class.
Create object using Object.clone()
This is also a way to have a new independent instance of a class.
NewClass obj = new NewClass(); NewClass obj2 = (NewClass) obj.clone();
Create new object using serialization and deserialization
If you have gone through this article, you can understand that serialization and de-serialization is also a way to have another instance of a class in system.
ObjectInputStream objStream = new ObjectInputStream(inputStream); NewClass obj = (NewClass ) inStream.readObject();
Create new object using reflection
Reflection is also a popular way to create new instances in most of available frameworks.
If you think I am missing any other possible way, please let me know.
Happy Learning !!