Getting All Constructors with getConstructors()
You'll learn how to retrieve all public constructors from a class for runtime inspection and invocation.
The Core Idea
The Reflection API allows you to discover what constructors a class has at runtime, even if you didn't write that class yourself. The getConstructors() method on a Class object returns an array of Constructor objects, each representing one public constructor defined in the class.
Think of it like getting a catalog of all the different ways you can build an instance of a class—every public "assembly instruction" the class offers.
How It Works
When you call getConstructors() on a Class object, Java scans the class definition and returns a Constructor<?>[] array. Each Constructor object in the array represents one public constructor and can tell you:
- What parameters it accepts
- What exceptions it throws
- Its modifiers (though it's always public if returned by
getConstructors())
Important: getConstructors() only returns public constructors. Private, protected, and package-private constructors are excluded. To access those, you'd need getDeclaredConstructors() (a different method not yet covered).
Typical Usage
Class<?> clazz = String.class;
Constructor<?>[] constructors = clazz.getConstructors();
System.out.println("String class has " + constructors.length + " public constructors:");
for (Constructor<?> constructor : constructors) {
System.out.println(constructor);
}
This code retrieves all public constructors from String and prints them, revealing the various ways you can create String objects.
Key Takeaway: Use getConstructors() on a Class object to retrieve an array of all public constructors, enabling runtime inspection of how instances can be created.