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

Invoking Private Constructors with setAccessible

Access and invoke private constructors by calling setAccessible(true), understanding security implications and use cases.

Invoking Private Constructors with setAccessible

You'll learn how to reflectively instantiate objects even when their constructors are private, and understand when this powerful technique is appropriate.

The Core Idea

Sometimes classes hide their constructors using the private modifier—perhaps to enforce the Singleton pattern, prevent direct instantiation, or control object creation through factory methods. Reflection lets you bypass this restriction by calling setAccessible(true) on the Constructor object before invoking it.

Think of it like having a master key that overrides locked doors in a building. Normally, you can't enter a private room, but reflection gives you special access when absolutely necessary.

How It Works

Once you obtain a private Constructor object via getDeclaredConstructor(), it's initially inaccessible. Calling setAccessible(true) tells the JVM to suppress access checks, allowing you to invoke newInstance() successfully.

Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
constructor.setAccessible(true);  // Bypass private access control
Singleton instance = constructor.newInstance();

Security and Use Cases

This technique has security implications. You're deliberately violating encapsulation and the designer's intent. Modern Java's module system may block these operations unless you explicitly open packages.

Legitimate uses include:

  • Testing frameworks that need to instantiate classes with private constructors
  • Serialization libraries reconstructing objects
  • Dependency injection frameworks managing object lifecycles
  • Deep cloning utilities

Avoid using setAccessible in regular application code—it's a tool for frameworks, not everyday programming.

Key Takeaway: You can invoke private constructors by calling setAccessible(true) on the Constructor object, but this breaks encapsulation and should only be used by frameworks or testing code where the security and design tradeoffs are justified.