12

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?

Community
  • 1
  • 1
Arun
  • 2,562
  • 6
  • 25
  • 43
  • You can create an object without new through: Reflection/newInstance, clone() and (de)serialization. I'm sure there are a few more I didn't think of. – Durandal May 17 '13 at 14:14

8 Answers8

15

You can do it using the Java Reflection API. That's how the Spring framework's DI works (instantiating object from xml).

Class<YourClass> c = YourClass.class;
YourClass instance = c.newInstance();

Also, Considering enum to be a special class, the instances of the enum are created without using new Operator.

public enum YourEnum { X, Y }
Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
  • 1
    Oops, but @Arun said: *. I said, internally the spring uses reflection utils to create an object with a new operator.* – Andremoniy May 17 '13 at 10:57
  • Class theClass = Class.forName("a.b.c.YourClass"); YourClass c = (YourClass) theClass.newInstance(); – arcy May 17 '13 at 10:57
  • @sanbhat: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() – Arun May 17 '13 at 10:58
12

An array initializer of the following form does not use new explicitly.

int ia[][] = { {1, 2}, null };

This creates an object ... by autoboxing:

Integer big = 9999;

Finally, the following result in the creation of objects somewhere in the program's lifecycle :-)

String s = "a literal";
enum Counting { ONE, TWO, FOUR, THREE_SIR }
Class c = String.class;

(And there are many, many ways to do it using library methods ... or native code)


Underneath the covers, any creation of a new object in pure Java involves either the new bytecode, or one of 3 new array bytecodes. That probably includes all of my examples.

Interestingly, Object.clone() and ObjectInputStream.readObject() both use "magic" mechanisms for creating instances that don't involve the above bytecodes, and don't call constructors in the normal way.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    With `"a literal"` and `String.class`, neither `new` nor `newarray` bytecodes are involved. Rather, an `ldc` instruction is used. It gets more complicated with today’s Java environments and string concatenation or lambda expressions… – Holger May 17 '23 at 15:53
7

You could use the JDBC's way

Class.forName("YOURCLASSNAME").newInstance()
Priyantha
  • 4,839
  • 6
  • 26
  • 46
fGo
  • 1,146
  • 5
  • 11
2

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

clone is used to make a copy of object. There are certain things which you should keep in mind while using clone method of Object.

  • implement "Cloneable" interface to each class which you want to clone. If a class does not implement "Cloneable" interface, clone method will throw "CloneableNotSupportedException". This interface does not contain any methods. It is just a marker interface.

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();

Other you can use Class.forName()

public static Class<?> forName(String className) throws ClassNotFoundException

Returns the Class object associated with the class or interface with the given string name.

Example -- Class exampleClass = Class.forName(yourtClass);

Read official docs

Priyantha
  • 4,839
  • 6
  • 26
  • 46
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
  • 1
    But I guess this seems to use new operator internally. http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/ – Arun May 17 '13 at 11:05
  • @Arun clone creates a new instance of the same class and copies all the fields to the new instance and returns it. It is not written anywhere that it is internally using new operator. – Nikhil Agrawal May 17 '13 at 11:11
2
   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
Priyantha
  • 4,839
  • 6
  • 26
  • 46
Muhammad Sadiq
  • 434
  • 4
  • 10
1

You can deserialize an object without invoking new.

Ok, you have to call new on the FileInputStream and the ObjectInputStream, but I assume that is fair use.

 FileInputStream fis = new FileInputStream("myClassInstance.ser");
 ObjectInputStream ois = new ObjectInputStream(fis);
 MyClass myObject = (MyClass)ois.readObject();
DeltaLima
  • 5,864
  • 1
  • 16
  • 32
0

AFAIK, Class.newInstance() and Constructor.newInstance() don't use the new keyword internally.

Other ways to create an instance without the new keyword:

  • Object.clone()
  • Serialization
Puce
  • 37,247
  • 13
  • 80
  • 152
0

There are only three standard ways to instantiate a class without the use of the new operator, and they are as follows:

  1. newInstance()
  2. clone()
  3. De-serialization
Z.I.J
  • 1,157
  • 16
  • 36
  • I can think of at least 2 other ways ... in addition to the 5 other ways shown as examples in my Answer. So your *"there are only three standard ways"* is some way off the mark. – Stephen C Dec 16 '15 at 06:26