Create an Object of class without new keyword

Ravi Chandola
Javarevisited
Published in
4 min readApr 13, 2023
Photo by Kenny Eliason on Unsplash

In Java, the new keyword is used to create a new instance of a class, which allocates memory for the object and initializes its state. However, there are some alternative ways to create an object without using the new keyword, which are as follows:

Using object deserialization: Objects can be created from serialized data stored in a file or over the network. The deserialization process creates an object from the serialized data without using the new keyword.

To create an object using serialization, the class must implement the Serializable interface. The ObjectInputStream class reads the serialized object from a file or network and returns the object

import java.io.*;

public class SerializationExample {
public static void main(String[] args) {
// Create an object
MyClass obj = new MyClass("Hello", 123);

// Serialize the object to a file
try {
FileOutputStream fileOut = new FileOutputStream("inst.serial");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.println("Object has been serialized");
} catch (IOException e) {
e.printStackTrace();
}

// Deserialize the object from the file
try {
FileInputStream fileIn = new FileInputStream("inst.serial");
ObjectInputStream in = new ObjectInputStream(fileIn);
MyClass obj2 = (MyClass) in.readObject();
in.close();
fileIn.close();
System.out.println("Object has been deserialized");
System.out.println("String value: " + obj2.str);
System.out.println("Int value: " + obj2.num);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

class MyClass implements Serializable {
public String str;
public int num;

public MyClass(String str, int num) {
this.str = str;
this.num = num;
}
}

Using reflection: The java.lang.reflect package provides classes and interfaces to create objects reflectively at runtime, without using the new keyword. Reflection allows you to create objects dynamically by invoking constructors or factory methods.

import java.lang.reflect.*;

class MyClass {
public String str;
public int num;

public MyClass(String str, int num) {
this.str = str;
this.num = num;
}

public void display() {
System.out.println("String value: " + str);
System.out.println("Int value: " + num);
}
}

public class ReflectionExample {
public static void main(String[] args) {

Class<?> clazz = MyClass.class;

// Create an object using reflection
MyClass obj = null;
try {
obj = (MyClass) clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}

// Set the values of the object
try {
Field strField = clazz.getDeclaredField("str");
strField.setAccessible(true);
strField.set(obj, "Hello");

Field numField = clazz.getDeclaredField("num");
numField.setAccessible(true);
numField.setInt(obj, 123);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}

// Call a method on the object
try {
Method displayMethod = clazz.getDeclaredMethod("display");
displayMethod.invoke(obj);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}

Class<?> clazz = MyClass.class; is creating a reference variable clazz of type Class<?> and initializing it with the Class object of MyClass by using the .class operator.

The Class object represents the class definition in the JVM, and contains information about the class such as its methods, fields, constructors, annotations, etc.

By assigning MyClass.class to clazz, we can use the clazz variable to access the class information and create objects of that class using reflection.

Note that we need to set the accessibility of the fields to true using the setAccessible() method, since the str and num fields are declared as private. Also, we need to catch several exceptions that may occur when using reflection, such as NoSuchFieldException, IllegalAccessException, NoSuchMethodException, and InvocationTargetException.

Using clone method: The Object class provides a clone method, which creates a new object with the same state as the original object. This method creates an object without using the new keyword, but it is important to note that the clone method creates a shallow copy of the object, which means that the object's references to other objects are not copied.

class MyClass implements Cloneable {
public String str;
public int num;

public MyClass(String str, int num) {
this.str = str;
this.num = num;
}

@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

public class CloningExample {
public static void main(String[] args) {
// Create an object
MyClass obj1 = new MyClass("Hello", 123);

// Clone the object
MyClass obj2 = null;
try {
obj2 = (MyClass) obj1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}

// Print the values of the original and cloned objects
System.out.println("Original object: " + obj1.str + " " + obj1.num);
System.out.println("Cloned object: " + obj2.str + " " + obj2.num);
}
}

Using dependency injection frameworks: Dependency injection frameworks like Spring and Guice provide a way to create objects without using the new keyword. These frameworks create objects by injecting their dependencies automatically based on configuration files or annotations.

Dependency injection is a design pattern that allows you to create an object and inject its dependencies. The dependencies are typically passed to the object through its constructor or setter methods.

Factory Method: A factory method is a static method that creates an object and returns it. The advantage of using a factory method is that it can return a cached instance of the object, which can improve performance. The factory method can also return a subclass of the object, depending on the input parameters.

In summary, while the new keyword is the most common way to create an object in Java, there are alternative ways to do so, such as object deserialization, reflection, clone method, and dependency injection frameworks.

--

--

Ravi Chandola
Javarevisited

As a technology enthusiast, I have a passion for learning and sharing my knowledge with others. https://www.linkedin.com/in/ravi-chandola-304522133