Program to demonstrate how to determine information about class constructor at runtime using Java Reflection API.
package com.hubberspot.reflection;
import java.lang.reflect.Constructor;
// Create a class Employee with few constructor
// having access modifiers as : public , private
// default and protected
class Employee {
public Employee(int salary, String name) {
}
private Employee(String name, int salary) {
}
Employee(String name) {
}
protected Employee(int salary) {
}
}
public class ConstructorFindings {
public static void main(String[] args) {
// Creating a instance of class Class of type Employee
Class employeeClass = Employee.class;
// object of class Instance has a method by name
// getConstructors() which returns back a list of
// public constructors in the form of array
// The array type is of Constructor class
Constructor[] constructors = employeeClass.getConstructors();
for(int i = 0; i < constructors.length; i++) {
// Constructor class defines a method called as getParameterTypes()
// which returns back an array of Class objects having metadata
// for types of arguments used in the constructor
Class[] parametersArr = constructors[i].getParameterTypes();
System.out.print("Constructor is : public having arguments as : ");
for(int j = 0; j < parametersArr.length; j++) {
String parameterType ="";
// printing the type of argument passed to the constructor
parameterType = parametersArr[j].getName();
System.out.print(parameterType+" ");
}
}
// In order to get information of constructors other than public
// we use getDeclaredConstructors() method on the instance of the
// Class (Employee). It returns back array of constructors having
// access modifiers including public.
constructors = employeeClass.getDeclaredConstructors();
System.out.println("\n\nEmployee has other constructor with type as : ");
for(int i = 0; i < constructors.length; i++) {
Class[] parametersArr = constructors[i].getParameterTypes();
for(int j = 0; j < parametersArr.length; j++) {
String parameterType ="";
parameterType = parametersArr[j].getName();
System.out.print(parameterType+" ");
}
}
}
}
Output of the program :
