[Solved] How to fix java.lang.InstantiationException

What is java.lang.InstantiationException?

A java.lang.InstantiationException is thrown when JVM cannot instantiate a type at runtime.

To make this definition more elaborate. A java.lang.InstantiationException can be thrown when you try to create an instance of a non-instantiable type or a legit concrete class without having nullary constructor, dynamically during runtime using Class.newInstance() method.

To be more specific, you get java.lang.InstantiationException under below circumstances.

  • Passing the fully qualified name of abstract class name or interface to Class.forName as a String while creating instance of Class
  • Creating Class instance using abstract class or interface or array or primitive type by using their “.class” attribute
  • Passing the name of Interface to Class.forName

In Java, you can create an instance of a class at runtime using Class type, provided that the given class is a concrete class.

Creating an instance using Class.newInstance of a known class

Class<Animal> c = String.class;
String str = c.newInstance();

Creating an instance using Class.newInstance of an unknown class loaded with Class.forName

Class c = Class.forName("java.lang.String");
String str = (String) c.newInstance();

These are the two ways of instantiating and we generally use either of one. But we may get java.lang.InstantiationException when we are instantiating in this way. Java enforce you to declare or handle java.lang.InstantiationException when you are using Class.newInstance() method to create instances. So, let’s discuss why do we get java.lang.InstantiationException with this style of coding.

When the Type is Non-instantiable

There are few types which we cannot instantiate. We cannot instantiate an abstract class, an interface, an Array or any Java primitive type using new keyword. Java compiler will throw error immediately if we are attempting that. However, we can also write code to create an instance of type using Class.newInstance. While loading the class we provide the class name withing double quotes to Class.forName() method or use the “.class” attribute the type which returns a Class object as shown above.

See also  Solving Int Cannot Be Dereferenced in Java

In this approach, there is a possibility that you can provide a class name which can’t be instantiated, and Java Compiler ignores them during compilation time. However, at runtime when JVM tries create an instance of that type, it realizes that it can’t be instantiated and throws java.lang.InstantiationException.

So, you need to go back and check if you are creating in this style, you are making sure that you are using concrete Java class only.

Below are few examples, in which java.lang.InstantiationException is thrown.

When you attempt to instantiate abstract class

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

abstract class Alpha {

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Class.forName("com.techstackjournal.Alpha");

 // Can also be written as, Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();
	}

}
Exception in thread "main" java.lang.InstantiationException
	at java.base/jdk.internal.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
	at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
	at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:350)
	at java.base/java.lang.Class.newInstance(Class.java:645)
	at com.techstackjournal.InitializationExceptionDemo.main(InitializationExceptionDemo.java:15)

When you attempt to instantiate interface type

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

interface Alpha {

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Class.forName("com.techstackjournal.Alpha");

 // Can also be written as, Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();
	}

}
Exception in thread "main" java.lang.InstantiationException: com.techstackjournal.Alpha
	at java.base/java.lang.Class.newInstance(Class.java:639)
	at com.techstackjournal.InitializationExceptionDemo.main(InitializationExceptionDemo.java:16)
Caused by: java.lang.NoSuchMethodException: com.techstackjournal.Alpha.<init>()
	at java.base/java.lang.Class.getConstructor0(Class.java:3508)
	at java.base/java.lang.Class.newInstance(Class.java:626)
	... 1 more

When the Type doesn’t have a Nullary Constructor

If the class that you are instantiating doesn’t contain a nullary constructor and you are attempting to create an instance of that class using Class.forName method, java.lang.InstantiationException will be thrown.

A nullary constructor is a constructor without any arguments.

So, when we try to instantiate a class using Class.newInstance() as below, it tries to create an instance using empty constructor (or nullary constructor). Since our code doesn’t have a nullary constructor JVM throws java.lang.InstantiationException. Look below to this code snippet on how we can resolve this kind of issues.

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

class Alpha {

	public Alpha(String arg1) {

	}

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Class.forName("com.techstackjournal.Alpha");

 // Can also be written as, Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();

	}

}
Exception in thread "main" java.lang.InstantiationException: com.techstackjournal.Alpha
	at java.base/java.lang.Class.newInstance(Class.java:639)
	at com.techstackjournal.InitializationExceptionDemo.main(InitializationExceptionDemo.java:20)
Caused by: java.lang.NoSuchMethodException: com.techstackjournal.Alpha.<init>()
	at java.base/java.lang.Class.getConstructor0(Class.java:3508)
	at java.base/java.lang.Class.newInstance(Class.java:626)
	... 1 more

How to fix java.lang.InstantiationException caused by nullary constructor

There are 2 solutions to fix this issue.

  1. First obvious solution is to add a constructor to the class without arguments. But sometimes it is possible that the class being used is within a jar file is not accessible to make changes to it, where our 2nd solution comes into the picture.
  2. If the above solution is not possible, may be due to the fact that the class is within a jar file, you can use the existing constructor explicitly while creating the instance using Class.getDeclaredConstructor(Class).newInstance(arguments)
See also  Finding Maximum of Three Numbers in Java

Fixing java.lang.InstantiationException by Adding Nullary Constructor

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

class Alpha {

	public Alpha(String arg1) {
		// do something
	}

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();

	}

}

You may have the code as given in the above code snippet which is causing java.lang.InstantiationException. I can fix that issue just by adding a nullary method or no-argument constructor as below.

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

class Alpha {
	
	public Alpha() {
		System.out.println("Success");
	}

	public Alpha(String arg1) {
		// do something
	}

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Alpha.class;
		Alpha a = (Alpha) c.newInstance();

	}

}

Fixing java.lang.InstantiationException by Calling Specific Constructor

As mentioned above, we can call a specific constructor while creating instance using newInstance method with the help of Class.getDeclaredConstructor method. The Class.getDeclaredConstructor method takes one or more arguments of type Class, which tells the JVM to look for constructors with that signature. For example, if I pass List.class and String.class as arguments, we are telling the JVM to look for a constructor that has its first argument as List and second argument as String. Then JVM will make use of that specific constructor to create the instance instead of searching for the default nullary constructor.

package com.techstackjournal;

import java.lang.reflect.InvocationTargetException;

class Alpha {

	public Alpha(String arg1) {
		System.out.println(arg1);
	}

}

public class InitializationExceptionDemo {

	public static void main(String[] args)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			NoSuchMethodException, SecurityException, ClassNotFoundException {
		Class c = Alpha.class;
		Alpha a = (Alpha) c.getDeclaredConstructor(String.class).newInstance("test");

	}

}