different ways of getting a new object in Java
October 9, 2012 Leave a comment
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"); c.newInstance();
– 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.
Deserialization
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
Recent Comments