Constructor class in Reflection API
java.lang.reflect package.
Constructor class allows you to get information about, and instantiate objects using, constructors dynamically at runtime.
newInstance().
Constructor class inherits the Executable class and implements the GenericDeclaration and Member interfaces.
Constructor Class
Constructor class:-
| S.No | Method | Use |
|---|---|---|
| 1 | getName() |
Returns the name of the constructor (same as class name). |
| 2 | getParameterTypes() |
Returns an array of Class objects representing the parameter types. |
| 3 | getModifiers() |
Returns the Java language modifiers (public, private, etc.) as an int. |
| 4 | newInstance(Object... initargs) |
Creates a new instance of the class represented by this constructor with specified arguments. |
| 5 | isVarArgs() |
Checks if the constructor accepts a variable number of arguments. |
import java.lang.reflect.*;
class Student
{
public String name;
private int age;
// Parameterized constructor
public Student(String name, int age)
{
this.name = name;
this.age = age;
}
// Default constructor
private Student()
{
this.name = "Default";
this.age = 0;
}
public void display()
{
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class MainApp
{
public static void main(String[] args) throws Exception
{
Class<?> c = Student.class;
// Get declared constructors
for (Constructor<?> constructor : c.getDeclaredConstructors())
{
System.out.println("\nConstructor Name: " + constructor.getName());
System.out.println("Modifiers: " + Modifier.toString(constructor.getModifiers()));
// Print parameter types
Class<?>[] params = constructor.getParameterTypes();
System.out.print("Parameter Types: ");
for (Class<?> p : params)
System.out.print(p.getSimpleName() + " ");
System.out.println();
// Access private constructors
constructor.setAccessible(true);
// Dynamically create object
Object obj;
if (params.length == 0)
obj = constructor.newInstance();
else
obj = constructor.newInstance("John", 25);
// Invoke display() method
Method displayMethod = c.getMethod("display");
displayMethod.invoke(obj);
}
}
}
Constructor Name: Student Modifiers: private Parameter Types: Name: Default, Age: 0 Constructor Name: Student Modifiers: public Parameter Types: String int Name: John, Age: 25
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.