DevNotes
Support
Reflection · Chapter 06

Constructors in Reflection

The Constructor API — getConstructors vs getDeclaredConstructors, private constructors, newInstance() with arguments, constructor metadata, exceptions and how frameworks create objects.

◷ 6 min read§ 16 sections? 6 interview questions{ } 23 code examples

#Introduction

In the previous chapter we learned how to inspect a class using the Class API. Now we'll learn how to inspect and invoke constructors using Reflection.

One of the biggest advantages of Reflection is that it lets us create objects dynamically at runtime, even when we don't know the class during compilation. This is used extensively by Spring, Hibernate, Jackson and JUnit.

#What is a Constructor?

A constructor is a special member of a class that is executed whenever an object is created.

Java
class Employee {
    Employee() {
        System.out.println("Employee Object Created");
    }
}

Normally we create an object like this:

Java
Employee emp = new Employee();

Here the compiler already knows the class name, the constructor and the object type. Reflection removes this compile-time dependency.

#The Constructor Reflection API

All constructor-related operations use java.lang.reflect.Constructor.

Class
Constructor
Create object

#Getting All Public Constructors

Java
public class Employee {
    public Employee() {
    }

    public Employee(String name) {
    }

    private Employee(int id) {
    }
}
Java
Class<?> cls = Employee.class;

Constructor<?>[] constructors = cls.getConstructors();

for (Constructor<?> c : constructors) {
    System.out.println(c);
}
Output
public Employee()
public Employee(java.lang.String)

Notice that the private constructor is not returned. (Parameter types are printed with their fully qualified names; if Employee were in a package, it would print public com.demo.Employee().)

#getConstructors() vs getDeclaredConstructors()

Java
Constructor<?>[] constructors = cls.getDeclaredConstructors();
Output
public Employee()
public Employee(java.lang.String)
private Employee(int)
MethodPublic constructorsPrivate / protected / package-private constructors
getConstructors()YesNo
getDeclaredConstructors()YesYes

(Constructors are never inherited, so neither method returns superclass constructors.)

#Getting a Specific Constructor

Java
public class Employee {
    public Employee() {
    }

    public Employee(String name) {
    }
}
Java
// no-argument constructor
Constructor<Employee> constructor = Employee.class.getConstructor();

// parameterized constructor
Constructor<Employee> constructor = Employee.class.getConstructor(String.class);

Notice: we specify parameter types, not values.

#Getting a Private Constructor

Java
class Employee {
    private Employee(int id) {
    }
}
Java
Constructor<Employee> constructor = Employee.class.getDeclaredConstructor(int.class);

constructor.setAccessible(true);   // since it is private

Now it can be used.

#Creating Objects Dynamically

The most important part.

Java
public class Employee {
    public Employee() {
        System.out.println("Employee Object Created");
    }
}
Java
Constructor<Employee> constructor = Employee.class.getConstructor();

Employee emp = constructor.newInstance();
Output
Employee Object Created

No new Employee() statement is used — Reflection creates the object.

Using a Parameterized Constructor

Java
public class Employee {
    public Employee(String name) {
        System.out.println(name);
    }
}
Java
Constructor<Employee> constructor = Employee.class.getConstructor(String.class);

Employee emp = constructor.newInstance("Rahul");
Output
Rahul

The arguments are supplied at runtime.

Using a Private Constructor

Java
class Employee {
    private Employee() {
        System.out.println("Private Constructor");
    }
}
Java
Constructor<Employee> constructor = Employee.class.getDeclaredConstructor();

constructor.setAccessible(true);

Employee emp = constructor.newInstance();
Output
Private Constructor

Reflection can invoke private constructors (subject to module/security restrictions in modern Java).

#Constructor Metadata

Java
Constructor<?> constructor = Employee.class.getConstructor(String.class);
Java
// Name — the class's binary name (com.demo.Employee if it is in a package)
System.out.println(constructor.getName());              // Employee

// Parameter count
System.out.println(constructor.getParameterCount());    // 1

// Parameter types
for (Class<?> type : constructor.getParameterTypes()) {
    System.out.println(type.getName());                  // java.lang.String
}

// Modifiers
int modifier = constructor.getModifiers();
System.out.println(Modifier.isPublic(modifier));        // true
System.out.println(Modifier.isPrivate(modifier));       // false

#Constructor Exceptions

ExceptionReason
NoSuchMethodExceptionConstructor not found
InstantiationExceptionClass cannot be instantiated (e.g. abstract class)
IllegalAccessExceptionConstructor not accessible
InvocationTargetExceptionThe constructor itself threw an exception (the original is in getCause())
Java
try {
    Constructor<Employee> constructor = Employee.class.getConstructor();
    Employee emp = constructor.newInstance();
} catch (Exception e) {
    e.printStackTrace();
}

#Internal Working of newInstance()

Constructor object
Access check
Allocate memory
Execute constructor
Return object
It behaves like the new keyword, but dynamically

#Real-World Usage

Spring Framework

Spring scans classes like:

Java
@Service
public class UserService {
}

and internally performs operations similar to:

Java
Class<?> cls = Class.forName(className);

Constructor<?> constructor = cls.getDeclaredConstructor();

Object bean = constructor.newInstance();

Thus Spring creates beans dynamically. (With constructor injection, Spring picks the constructor that takes the dependencies and passes the beans as arguments.)

Hibernate

When Hibernate reads rows from the database, it creates entity objects using Reflection instead of writing new Employee():

Java
@Entity
public class Employee {
}

Jackson

While converting JSON into Java objects:

JSON
{
  "name": "Rahul"
}

Jackson first creates an object using Reflection (usually via the no-arg constructor) and then populates it.

#Class.newInstance() (Deprecated)

Older Java versions allowed:

Java
Employee emp = Employee.class.newInstance();

Problems:

  • Works only with an accessible no-argument constructor.
  • Poor exception handling — it rethrows any exception from the constructor directly, even checked ones the caller doesn't declare.

It is deprecated since Java 9. Preferred approach:

Java
Employee emp = Employee.class
        .getDeclaredConstructor()
        .newInstance();

#Interview Questions

Q1Which class represents constructors in Reflection?

java.lang.reflect.Constructor.

Q2Difference between getConstructor() and getDeclaredConstructor()?
MethodPublicPrivate
getConstructor()✓✗
getDeclaredConstructor()✓✓
Q3Difference between getConstructors() and getDeclaredConstructors()?
MethodReturns
getConstructors()All public constructors
getDeclaredConstructors()All constructors declared in the class
Q4Which method creates an object dynamically?

constructor.newInstance().

Q5Can Reflection invoke a private constructor?

Yes — by calling setAccessible(true) before newInstance().

Q6Why is Class.newInstance() deprecated?

Because it supports only no-argument constructors and has poor exception handling. Use getDeclaredConstructor().newInstance() instead.

#Key Points to Remember

  • Constructors are represented by java.lang.reflect.Constructor.
  • Reflection can inspect both public and private constructors.
  • getConstructor() returns only public constructors; getDeclaredConstructor() can access private ones.
  • newInstance() creates objects dynamically, including with parameters.
  • setAccessible(true) enables access to private constructors (subject to module restrictions).
  • Spring, Hibernate and Jackson use constructor reflection to create objects at runtime.

#Chapter Summary

The Constructor API enables Java programs to inspect constructors, retrieve metadata and create objects dynamically. This forms the foundation of dependency injection, ORM frameworks, serialization libraries and many plugin systems. Mastering constructor reflection is essential for understanding how modern Java frameworks instantiate objects without explicitly using the new keyword.