ReviseAlgo Logo

Reflection

Inspecting Constructors

Inspect constructors and access parameter definitions using reflection.

Interview: Commonly tested on constructor lookup and instantiating classes with parameters.

Last Updated: June 13, 2026 8 min read

Java Reflection allows inspecting class constructors, identifying parameter types, and checking visibility scopes.

Core Idea

Constructors can be queried dynamically by matching argument type arrays.

Why It Matters

Dependency Injection frameworks need this to find constructors, determine their dependencies, and inject beans.

Interview Lens

Focuses on constructor lookups and identifying constructors of non-static inner classes.

Constructor Querying

To inspect constructors:

  • getDeclaredConstructors() returns all constructors declared in the class.
  • getParameterTypes() returns an array of Class objects representing the parameter types in order.
  • Bypassing private modifiers allows instantiating classes with private constructors (often used to verify singleton testing).

Code Walkthrough

This program inspects a class's constructors and prints their parameter counts.

import java.lang.reflect.Constructor;

public class ConstructorInspectionDemo { public static void main(String[] args) { Constructor[] constructors = String.class.getDeclaredConstructors();

System.out.println("Total String constructors: " + constructors.length); for (Constructor c : constructors) { System.out.println("Params: " + c.getParameterCount()); } } }

Interview-Relevant Information

Q: How does a non-static inner class constructor differ from a static nested class?
Answer: Non-static inner class instances hold an implicit reference to their enclosing outer class instance. Consequently, the compiler inserts the outer class class-type as the first parameter in the inner class constructor. Reflection inspections will show this extra parameter, whereas static nested class constructors do not have it.

Quick Checklist

How do you count constructor parameters? What implicit parameter does a non-static inner class constructor receive? If yes, you understand constructor reflection.

Use Cases

Determining dependency parameters in Spring DI containers.

Dynamic instantiation systems mapping configuration parameters.

Common Mistakes

Assuming a constructor with no parameters is present when custom constructors are declared (the compiler only adds the default constructor if no other constructors exist).

Forgetting parameter matching order during constructor lookup.