Monday, 19 September 2011

Number of ways to create java object

1)Ex1 obj1j=new Ex1;(using new operator)

2)Class c = Class.forName("java.lang.String"); (using Class.forName also called reflection)

3)MyObject obj=(MyObject) obj.clone();(using cloning)

4)we will create the objects using factory design pattern (but internally we are using new operator).

5)with the help of deserialization we will get the object(in serialization we are creating object to file and in deserialization we are getting the object from file).


Some in put from google
1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99 of objects are created in this way.
MyObject object = new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object= (MyObject) Class.forName( subin.rnd.MyObject ).newInstance();
3. Using clone()The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
5. Using class loaderone more is through creation of object using classloader
like

this.getClass().getClassLoader().loadClass( com.amar.myobject ).newInstance();

2 comments:

Related Posts Plugin for WordPress, Blogger...