Wednesday, 6 April 2011

Different Ways to Create Objects

There are at least four ways to create a new object:

1) Using new

    Car obj = new Car();

2) Using clone

    Car a = new Car();
    Car b =
(Car) a.clone();

3) Using Class.forName(...)

    Car obj2 = (Car) Class.forName("Car").newInstance();

4) De-serializing

    InputStream instream = new FileInputStream("Car.ser");
    ObjectInputStream in =
new ObjectInputStream(instream);
    Car object =
(Car) in.readObject();

although technically, a de-serialized object is an old object that’s been reloaded - possibly...

1 comment:

Anonymous said...

Captain, first time reading you blog and gotta say that I'm enjoying it a lot. (I've just added it to my read list)

I guess is never too late to comment. But here are two cents on the "de-serializing" way of create an object.

I think is worth to mention all the cons that pure java object serialization brings to the table. (e.g. incompatible if the class changed due a new field, or if different version of jvm was used, etc...)

But it's also good to mention new and better ways to serialize, perhaps the most used nowadays JSON via jackson it provides you with a huge amount of customization and solves the after-mentioned issues