Getting Constructor Objects via Reflection
What you'll learn: How to retrieve Constructor objects from a class using reflection, whether they're public or private.
The Core Idea
Before you can create an instance reflectively using a specific constructor, you need to get a Constructor object that represents that constructor. Java's Class API provides methods to retrieve constructors based on their parameter types and visibility.
Think of it like looking up a recipe in a cookbook. You need to first find the recipe (the constructor) before you can follow its instructions to bake a cake (create an instance).
Two Primary Methods
getConstructor() — Public Constructors Only
Use Class.getConstructor(Class<?>... parameterTypes) to retrieve a public constructor matching the specified parameter types:
Class<?> clazz = MyClass.class;
Constructor<?> publicCtor = clazz.getConstructor(String.class, int.class);
// Retrieves public constructor: MyClass(String, int)
If no matching public constructor exists, NoSuchMethodException is thrown.
getDeclaredConstructor() — Any Declared Constructor
Use Class.getDeclaredConstructor(Class<?>... parameterTypes) to retrieve any constructor (public, private, protected, or package-private) declared in that specific class:
Constructor<?> privateCtor = clazz.getDeclaredConstructor(String.class);
// Retrieves declared constructor: MyClass(String), even if private
This is essential when you need to access private constructors for frameworks, testing, or singleton patterns.
Specifying Parameter Types
Pass Class objects representing each parameter type in order. For a no-argument constructor, pass no arguments:
Constructor<?> defaultCtor = clazz.getDeclaredConstructor();
// No-arg constructor
Key Takeaway: Use getConstructor() to retrieve public constructors and getDeclaredConstructor() to access any constructor regardless of visibility, specifying parameter types as Class arguments to identify the exact constructor you need.