Last Updated:

How do I instantiate any class in Java without the new keyword?

How to Instantiate a Class Without the New Keyword

Below we will look at 5 ways (for sure there are even more):

  • Class.forName()
  • ClassLoader loadClass()
  • clone()
  • Deserialization
  • Reflection API

Using the forName() + newInstance() methods of the Class class

 

As you can see, we loaded the class into memory, then got an instance of that class with the help and by casting the type got the desired object.forName()newInstance()

Using the loadClass() method

This method is very similar to the previous one and essentially does the same thing, but with the help of ClassLoader:

 

Using the clone() method of the Object class

Get a new instance by cloning an existing object:

Using serialization and deserialization

Pass the existing one as a parameter to the class constructor and call to get an instance of the class.InputStreamObjectInputStreamreadObject()

Using the Reflection API

This is perhaps the most popular way to create an instance of a class after using the . Reflection is used in most modern Java frameworks:new

Read more about this method in the official documentation.

I'm sure there are other ways to create a new instance of a class without a keyword, so write in the comments if you know one.new

Subscribe to new articles on Java and Android!