CodeBlanks Logo Icon CodeBlanks

getDeclaredConstructors

Learn constructor listing with getDeclaredConstructors.

Constructors with getDeclaredConstructors

Class.getDeclaredConstructors() returns all constructors of a class, including private ones. getConstructors returns only the public constructors.

Example: Constructor<?>[] cs = Book.class.getDeclaredConstructors(). In the returned array, c.getParameterCount() gives the parameter count. You fetch a single constructor not by name but by parameter types: getDeclaredConstructor(String.class).

Creating instances with newInstance

To create a new instance from a Constructor object you use newInstance(args). This is the reflection equivalent of a regular new call.

Example: Book b = (Book) c.newInstance("Java"). Here c is a Constructor<Book>. The parameter count and types must match the constructor; otherwise an exception is thrown. This pattern is the basis of frameworks creating instances from class names.

Practice Create a Book with Constructor.newInstance

Define a Book class with a public String title field and a public Book(String title) constructor. Get the constructor with Book.class.getDeclaredConstructor(String.class). Create an instance with newInstance("Java") and print the title field with System.out.println. Add throws Exception to main.

Starter code

Main.java
import java.lang.reflect.Constructor;

// Define Book (title field and constructor)
// Get the constructor with getDeclaredConstructor
// Create an instance with newInstance, print title

Sample solution

Main.java
import java.lang.reflect.Constructor;

class Book {
    public String title;
    public Book(String title) {
        this.title = title;
    }
}

public class NewInstanceExample {
    public static void main(String[] args) throws Exception {
        Constructor<Book> c = Book.class.getDeclaredConstructor(String.class);
        Book b = c.newInstance("Java");
        System.out.println(b.title);
    }
}

Expected output

Java

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method returns all constructors, including private ones?

  • getDeclaredConstructors Correct answer
  • getConstructors
  • getMethods
  • getFields

Explanation: getDeclaredConstructors returns all constructors.

2 Match the Constructor methods

Term Meaning
getDeclaredConstructors All constructors
getConstructors Public constructors
newInstance Create an instance
getParameters Get parameters

3 Complete the newInstance call

Question
Object obj = constructor.____(args);
Answer
Object obj = constructor.newInstance(args);

Explanation: newInstance creates a new instance.

All lessons in Advanced