Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Class.getDeclaredConstructor — look up a declared constructor

Look up a constructor by its exact parameter types, then create an object in a separate step. The example uses the public no-argument StringBuilder constructor without bypassing access checks.

Version: Java SE 21

Syntax

public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
    throws NoSuchMethodException, SecurityException

In Java SE 21, Class.getDeclaredConstructor finds one constructor declared by the class represented by Class<T> and returns a java.lang.reflect.Constructor<T>. It can find non-public constructors, including private ones. getConstructor searches only public constructors. Constructors are not inherited.

Pass the exact formal parameter types in declaration order, not argument values. Calling getDeclaredConstructor() with no arguments looks for a constructor with no parameters. int.class and Integer.class are not interchangeable: lookup does not box types or select an overload based on assignability. For a non-static member class, pass the enclosing class's type first at lookup and an enclosing instance first at invocation.

If no constructor matches, lookup throws NoSuchMethodException. In Java SE 21, an installed security manager can also deny lookup, causing SecurityException. Finding a constructor neither grants permission to invoke it nor creates an object.

Call Constructor.newInstance with the argument values to create the object. It throws IllegalAccessException if access checks reject the invocation. If the constructor itself throws an exception, newInstance wraps it in InvocationTargetException. The example uses public StringBuilder() without bypassing access checks.

Examples

import java.lang.reflect.Constructor;

public class Main {
    public static void main(String[] args) throws ReflectiveOperationException {
        Constructor<StringBuilder> constructor = StringBuilder.class.getDeclaredConstructor();
        StringBuilder builder = constructor.newInstance();
        System.out.println(builder.append("Java").toString());
    }
}

Result

Java

The first statement looks up the constructor; the second creates an empty `StringBuilder`. After appending the text, the program prints `Java`.

Related lessons

  • Java · Lesson 13 · Advanced · Version: 2

Sources