We all know how to create objects of any class. The simplest method to create an object in Java is using new keyword. Let’s explore other methods to create objects without new keyword.
1. Using Class.newInstance()
Class ref = Class.forName("DemoClass");
DemoClass obj = (DemoClass) ref.newInstance();
The Class.forName()
loads the DemoClass in memory. To create an instance of this class, we need to use newInstance()
.
2. Using ClassLoader
Just like the above method, the class loader’s loadClass()
method does the same thing. It creates a new instance of a class using an existing instance of the same class.
instance.getClass().getClassLoader().loadClass("NewClass").newInstance();
3. Using Object.clone()
The clone() method is also a way to have a new independent instance of a class.
NewClass obj = new NewClass();
NewClass obj2 = (NewClass) obj.clone();
4. Using Serialization and Deserialization
If you have gone through serialization basics, you can understand that serialization and de-serialization are also a way to have another instance of a class in the runtime.
ObjectInputStream objStream = new ObjectInputStream(inputStream);
NewClass obj = (NewClass ) inStream.readObject();
5. Using Reflection
Reflection is also a popular way to create new instances in most of the available frameworks.
private <T> T instantiate(Class<?> input, Object parameter) {
try {
Constructor<?> constructor = ConstructorUtils
.getMatchingAccessibleConstructor(input, parameter.getClass());
return (T) constructor.newInstance(parameter);
} catch (Exception e) {
//handle various exceptions
}
}
If you think I am missing any other possible way, please let me know.
Happy Learning !!