Exception Handling in Reflective Instantiation
What You'll Learn
You'll learn how to properly catch and handle the four main exceptions that can occur when creating objects via reflection.
The Four Exception Types
When using Constructor.newInstance() or related reflection APIs, Java requires you to handle several checked exceptions:
1. InstantiationException
Thrown when you try to instantiate an abstract class or an interface. It's like trying to build a blueprint instead of an actual house.
2. IllegalAccessException
Occurs when you attempt to invoke a constructor you don't have permission to access (even if you forget to call setAccessible(true) on a private constructor).
3. InvocationTargetException
This is a wrapper exception—it occurs when the constructor itself throws an exception during execution. The actual cause is nested inside via getCause(). Think of it as a delivery service reporting "your package had a problem" while the real issue is inside the box.
4. NoSuchMethodException
Thrown when you request a constructor with parameter types that don't exist in the class. You asked for a constructor that simply isn't there.
Practical Handling Pattern
try {
Class<?> clazz = MyClass.class;
Constructor<?> ctor = clazz.getDeclaredConstructor(String.class);
ctor.setAccessible(true);
Object instance = ctor.newInstance("argument");
} catch (InstantiationException e) {
// Can't instantiate: abstract class or interface
} catch (IllegalAccessException e) {
// Access denied despite setAccessible attempt
} catch (InvocationTargetException e) {
// Constructor threw an exception; inspect e.getCause()
} catch (NoSuchMethodException e) {
// Constructor with those parameters doesn't exist
}
Key Takeaway: Reflective instantiation requires handling four distinct checked exceptions—InstantiationException, IllegalAccessException, InvocationTargetException, and NoSuchMethodException—each signaling a different failure mode in the object creation process.