Course contentsShow
← Java
Lesson 2364 of 2,87045. Reflection APIFree lesson

Accessing Private Constructors Reflectively

Instantiate classes through private constructors using Constructor.setAccessible, even for singleton patterns.

Accessing Private Constructors Reflectively

What you'll learn: How to instantiate objects from classes with private constructors using reflection, even breaking singleton patterns.

Why Private Constructors Exist

Some classes declare their constructors private to control object creation—singleton patterns, factory-controlled instantiation, or utility classes all use this technique. Normally, you cannot call new on such classes from outside code.

Breaking Through with Reflection

Just as setAccessible lets you access private fields and methods, it works on constructors too. Here's how:

public class Singleton {
    private static Singleton instance = new Singleton();
    
    // Private constructor prevents external instantiation
    private Singleton() {
        System.out.println("Singleton created");
    }
    
    public static Singleton getInstance() {
        return instance;
    }
}

// In another class:
Class<?> clazz = Singleton.class;
Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);  // Bypass the private access

// Create a new instance, violating singleton pattern!
Singleton newInstance = (Singleton) constructor.newInstance();

The Power and Danger

By calling setAccessible(true) on a private constructor, you can create instances that the class designer never intended. This completely breaks encapsulation—you could have multiple instances of a "singleton" or bypass validation logic embedded in factory methods.

Think of it like this: A private constructor is like a locked factory door. Reflection is a master key that opens any door, regardless of the "Authorized Personnel Only" sign.

Practical Applications

While this violates design intent, frameworks use this technique for dependency injection, testing (creating mock objects), and deserialization where they need full control over object creation.

Key Takeaway: Using Constructor.setAccessible(true) on private constructors allows reflective instantiation of any class, even those designed to prevent it—powerful for frameworks but dangerous for encapsulation.