Different Ways to Create Objects in Java

Using new Operator

Just like TestClass obj = new TestClass();

Using Reflection

Get the Class object and call newInstance API.

Class<ReflectionCreateObjects> clazz = ReflectionCreateObjects.class;
Constructor<ReflectionCreateObjects> constructor = clazz.getConstructor();
ReflectionCreateObjects obj = constructor.newInstance();

For more in-depth knowledge , please read Java Reflection: Create Objects

Using Cloning
TestClass obj = new TestClass();
TestClass clonedObj = obj.clone();

For more in-depth knowledge , please read Prototype

Using Serialization and Deserialization

First save the Object in a file using Serialization and then create the Object as many times by reading the saved file contents by using Deserialization.

Step 1 : Serialize – Write the Object into a file.

TestClass obj = new TestClass();
FileOutputStream fos = new FileOutputStream("testfile.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);

Step 2 : Deserialize – Read the Object from  the file.

FileInputStream fis = new FileInputStream("testfile.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
TestClass obj1= (TestClass) ois.readObject();

For more in-depth knowledge , please read Serialization in Java

Leave a Reply

Your email address will not be published. Required fields are marked *