How do you create an Object instance without using new?

By Atul Chavan - 1:25 AM

There are many ways to create an object without new operator :-

1. Using newInstance method of Class class

Eg: Class clas = Class.forName("NewClass");
NewClass obj = (NewClass) clas.newInstance();
- Class.forName() loads the class and to create an object, we need to use newInstance() method of Class class.

2. Using clone() of java.lang.Object

Eg: NewClass obj = new NewClass();
NewClass obj2 = obj.clone();
- Creates copy of an existing object

Read Here : The Psychology Behind Why We Like, Share and Comment on Facebook

3. Using Object Deserialization

Eg : ObjectInputStream objStream = new ObjectInputStream(inputStream );
NewClass obj = (NewClass ) inStream.readObject();

4. Using ClassLoader

Eg: getClass().getClassLoader().loadClass("NewClass").newInstance();

5. Using Reflection

Eg: constructor.newInstance() and class.newInstance()

6. Also, it can be created using Factory Method.

  • Share:

You Might Also Like