How many type to create Object in Java

object create
  1. Using Class.forName()
  2. ClassLoader loadClass()
  3. Using clone()
  4. Deserialization
  5. 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.
instance.getClass().getClassLoader().loadClass("NewClass").newInstance();
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();
Using Reflection
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

Post a Comment

0 Comments

Recent in Recipes

3/Food/post-list