top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can we Create Object without using the keyword “new” in java

+3 votes
418 views
How can we Create Object without using the keyword “new” in java
posted Feb 1, 2014 by Prachi Agarwal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Yes you can do this with the help of Reflection.

public class Hello {
  public void display() {
    System.out.println("Hello World");
  }
  public static void main(String args[]) throws Exception {
    Class c1 = Class.forName("Hello"); // throws ClassNotFoundException Object obj1 =       c1.newInstance( ); // throws InstantiationException and // IllegalAccessException
    Hello h1 = (Hello) obj1;
    h1.display();
  }
}

1 Answer

0 votes

1) your could use the jdbc's way

Class.forName("YOURCLASSNAME").newInstance()

2) You can use clone method to create a copy of object without new operator.

Example for String class

String sample = new String();

Now we are not going to use new operator and we will create a new object

String sampleClone = sample.clone();
answer Feb 1, 2014 by Jai Prakash
...