How do you create an Object instance without using new?

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.
How do you create an Object instance without using new? How do you create an Object instance without using new? Reviewed by Atul Chavan on 1:25 AM Rating: 5
Powered by Blogger.