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

Getting Declared Constructors Including Private Ones

Use getDeclaredConstructors() to access all constructors regardless of visibility, including private ones.

Getting Declared Constructors Including Private Ones

What you'll learn: How to use getDeclaredConstructors() to access all constructors of a class, including private ones that getConstructors() cannot see.

The Core Difference

In the previous lesson, you learned that getConstructors() only returns public constructors. But what if a class uses private constructors for singleton patterns, factory methods, or other design patterns? That's where getDeclaredConstructors() comes in.

The getDeclaredConstructors() method retrieves every constructor declared directly in the class, regardless of visibility: public, protected, package-private, and private. This gives you complete visibility into how a class can be instantiated.

Why This Matters

Think of getConstructors() as looking through the front door—you only see what's publicly accessible. But getDeclaredConstructors() is like having blueprints to the entire building—you see all the construction methods, even the hidden ones.

This is crucial when:

  • Analyzing frameworks that use private constructors
  • Working with serialization libraries that need to bypass normal construction
  • Building testing tools that need complete class introspection
  • Understanding singleton or utility class implementations

Key Signature

Constructor<?>[] getDeclaredConstructors()

This method returns an array of Constructor objects representing all constructors declared in the class, regardless of access level. Unlike getConstructors(), it won't climb up to superclasses—it only shows constructors declared in this specific class.

Important Distinction

  • getConstructors() → only public constructors (but includes inherited public behavior rules)
  • getDeclaredConstructors() → all constructors (public, protected, package-private, private) declared in this class only

Key Takeaway: Use getDeclaredConstructors() when you need complete visibility into all constructors of a class, including private ones that are hidden from normal access and from getConstructors().