Ways of Creating Object in Java

1- By new Operator
   
     Test t = new Test();

2- With the help of Reflection

   try {
  checkDo cc = (checkDo)Class.forName("checkDo").newInstance();
} catch (InstantiationException e) {
  e.printStackTrace();
} catch (IllegalAccessException e) {
  e.printStackTrace();
} catch (ClassNotFoundException e) {
  e.printStackTrace();
}


3- By Using Clone Method 


checkDo cc = new checkDo();
try {
  checkDo  ct = (checkDo)cc.clone();
} catch (CloneNotSupportedException e) {
  e.printStackTrace();
}


4- If class already provide the getInstancemethod

Runtime r = Runtime.getRuntime();
DateFormat df = DateFormat.getInstance();


5- By Using Deserialization 


FileInputStream fis = null;
try {
  fis = new FileInputStream("abc.ser");
  ObjectInputStream ois = new ObjectInputStream(fis);
  checkDo t = (checkDo)ois.readObject();
} catch (IOException | ClassNotFoundException  ex) {
  ex.printStackTrace();
}


Comments