We all know how to create objects of any class. Right?? Simplest is using new keyword. In this post, I will list down all other approaches in my knowledge.
- Using Class.forName()
- ClassLoader loadClass()
- Using clone()
- Using reflection
Note: I am writing pseudo code only. For building complete fully working sample code, please read about related feature.
Using newInstance method of Class class
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 newInstance().
Using class loader’s loadClass()
Just like above mechanism, class loader’s loadClass() method does the same thing.
Using clone() of java.lang.Object
This is also a way to have a new independent instance of a class.
NewClass obj = new NewClass(); NewClass obj2 = (NewClass) obj.clone();
Using Object 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();
This is also a popular way to create new instances in most of available frameworks.
constructor.newInstance(); or class.newInstance();
If you think I am missing any other possible way, please let me know.
Happy Learning !!