Instantiate objects without using new operator

2020-02-08 21:47发布

In one of the java interview, the following question is asked:

In java is there a way to instantiate an object without using new operator? I replied to him that there is no other way of instantiation. But he asked me how an object in java is instantiated with the configurations in an xml file in java(in spring framework). I said, internally the spring uses reflection utils to create an object with a new operator. But the interviewer was not convinced with my answer.

I saw this link to be useful but there is a new operator indirectly involved in one or the other internal methods.

Is there really a way to instantiate objects in java without using new operator?

8条回答
【Aperson】
2楼-- · 2020-02-08 22:14
   import java.io.FileInputStream;
   import java.io.FileOutputStream;
   import java.io.ObjectInputStream;
   import java.io.ObjectOutputStream;
   import java.io.Serializable;

   public class ObjectCreateDifferentWays {

       public static void main(String[] args) throws Exception {
           ///1st Way with newInstance()
           Class cls = Class.forName("Student");
           Student ob1 = (Student) cls.newInstance();
           ob1.display();

           ///2nd Way with new Operator
           Student ob2 = new Student();
           ob2.display();

           //3rd Way with clone
           Student ob3 = (Student) ob2.clone();
           ob3.display();


           //4th Way with Deserialization
           FileOutputStream out = new FileOutputStream("file.txt");
           ObjectOutputStream obOut = new ObjectOutputStream(out);
           obOut.writeObject(ob2);
           obOut.flush();

           FileInputStream fIn = new FileInputStream("file.txt");
           ObjectInputStream obIn = new ObjectInputStream(fIn);

           Student ob4 = (Student) obIn.readObject();
           ob4.display();
       }
   }


   class Student implements Cloneable, Serializable {
       public void display() throws Exception {
           System.out.println("Display ");
       }@
       Override
       protected Object clone() throws CloneNotSupportedException {
           return super.clone();
       }
   }

There are some ways to create object in Java 1) newInstance() method 2) new operator 3) clone() method 4) Deserialization

查看更多
叛逆
3楼-- · 2020-02-08 22:15

your could use the jdbc's way

Class.forName("YOURCLASSNAME").newInstance()
查看更多
登录 后发表回答