different ways of getting a new object in Java

For now I can think of getting a new object in 4 different ways

  • ‘new’ operator
  • reflection
  • deserialization
  • cloning

Using new operator

MyClass mc = new MyClass();

– Here MyClass.java availability will be checked at compile time.
– This is the most common way of creating objects in day-2-day activities of java programmer

using Class.forName(“<fully-qualified-class-name>”)

Class c = Class.forName("com.techforum.MyClass");

– Here code will compile without any issues, ie, with/without presence of MyClass.java in the classpath. But at runtime if the class is not found then it will throw run time exception. For this reason we are forced to handle ClassNotFoundException, it is an compile time exception, while loading a class at runtime

Using clone method

MyClass mc = new MyClass();
MyClass mcClone = mc.clone();

– Here we should make sure MyClass.java is implementing Cloneable interface in order to clone its object.


ObjectInputStream ois = new ObjectInputStream(is);
// Here is 'is' is stream representing the flat file
// that is generated while serializing the object
MyClass object = (MyClass) ois.readObject();

– Here we should make sure we are implementing Serializable interface if we wanna serialize/deserialize object


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


Mostly technology with occasional sprinkling of other random thoughts


Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates


A topnotch WordPress.com site


Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: