Facebook

For any corporate training requirements Please mail To sudhakar@qtpsudhakar.com
Course Name Date Time Duration Type Location
WhatsApp to 91-8328152362 for address details of AnyTechLabs
Selenium + Appium 27th February 2019 7.00 AM IST to 8:45 AM IST 45 Days Class Room + Online AnyTechLabs
Selenium + Appium 9th March 2019 9.00 AM IST to 2.00 PM IST 5 WeekEnds Class Room + Online AnyTechLabs

A book "Cracking the QTP interview" authored by Sudhakar.Read More. Buy From FlipKart

Tuesday, March 12, 2019

Different ways to create Instance in Java

import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;

public class WaysToCreateObjects {

 public static void main(String[] args)
   throws InstantiationException, IllegalAccessException, ClassNotFoundException, CloneNotSupportedException,
   IOException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

  // method1 : Standard Technique
  Sample insta1 = new Sample();
  System.out.println("instance1 created");

  // method2 : By taking class name as string in Class
  Sample insta2 = (Sample) Class.forName("com.batch.ques.Sample").newInstance();
  System.out.println("instance2 created");

  // method3 : Creating new instance from another instance
  Sample insta3 = insta2.getClass().newInstance();
  System.out.println("instance3 created");

  // method4 : Creating new instance using class static method
  Sample insta4 = Sample.class.newInstance();
  // Sample.class.getConstructor().newInstance();
  System.out.println("instance4 created");

  // method5 : Reading new instance from Object Stream
  ObjectInputStream strm = new ObjectInputStream() {
  };
  Sample insta5 = (Sample) strm.readObject();
  System.out.println("instance5 created");

  // method6 : Cloning new instance from other instance
  /*
   * For cloning you must make sure that the class is implemented with Cloneable
   * interface and should have clone() method imlementation
   * 
   */
  Sample insta6 = (Sample) insta1.clone();
  System.out.println("instance6 created");
 }
}

No comments :

Post a Comment