Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Selecting and invoking a constructor with reflection

Select the single `@Inject` constructor or fall back to a no-argument constructor when none is marked. Check parameter types and access before invoking it.

Version: Java SE 21

Syntax

import java.lang.reflect.Constructor;

Constructor<?>[] candidates = type.getDeclaredConstructors();
Constructor<?> ctor = type.getDeclaredConstructor(parameterTypes); // Class<?>...; exact signature
Class<?>[] formalTypes = ctor.getParameterTypes();
boolean marked = ctor.isAnnotationPresent(Inject.class);
if (!ctor.canAccess(null)) {
    ctor.setAccessible(true);
}
Object instance = ctor.newInstance(arguments); // arguments is Object[]

In Java SE 21, a java.lang.reflect.Constructor<T> represents one specific constructor. Class.getDeclaredConstructors() includes non-public constructors and promises no order; Class.getConstructors() returns only public constructors. Select the sole @Inject constructor. If several are marked, report ambiguity rather than taking the first. If none is marked, use Class.getDeclaredConstructor(); it throws NoSuchMethodException if there is no no-argument constructor.

Constructor.isAnnotationPresent(Inject.class) checks whether the constructor itself, not its parameters, has the specified runtime-visible annotation. The example defines its own @Inject marker with RetentionPolicy.RUNTIME; the annotation does not supply dependencies. Constructor.getParameterTypes() returns Class<?>[] in declaration order, empty if there are no parameters. It reports erased types, not argument values or generic details. Lookup with getDeclaredConstructor(...) requires exact types, such as int.class, not Integer.class, for an int parameter.

Constructor.setAccessible(true) suppresses Java language access checks for that reflected object without changing the constructor's modifiers. Check canAccess(null) first. For a private constructor in another module, the package must be open to the caller's module; exporting it alone is not enough. If module access rules prevent suppression, setAccessible(true) throws InaccessibleObjectException, whereas trySetAccessible() returns false. A security manager can deny either request with SecurityException. Independently of the security manager, calling setAccessible(true) on a constructor of java.lang.Class throws SecurityException even if the package is open. For such a constructor, trySetAccessible() returns false unless a security manager denies the request. setAccessible(false) re-enables checks for that object.

Constructor.newInstance(Object...) invokes the already selected constructor and returns a new instance; it does not resolve overloads. Supply arguments in parameter order. Unboxing and widening primitive conversions are allowed, but narrowing is not. A constructor's varargs parameter takes one array as its final argument; put that array inside an outer Object[] or cast it to Object so the reflective call does not treat its elements as separate arguments. For an inner class declared in a non-static context, supply the enclosing instance first.

IllegalArgumentException can mean the wrong number or incompatible types of arguments; IllegalAccessException means invocation was denied while access checks were active, and InstantiationException signals an attempt to instantiate an abstract class. An exception thrown by the constructor is wrapped in InvocationTargetException; inspect getCause(). A failure in the selected constructor is not a reason to fall back to the no-argument constructor.

Examples

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CONSTRUCTOR)
@interface Inject {}

public class Main {
    static <T> T create(Class<T> type) throws ReflectiveOperationException {
        Constructor<?> selected = null;
        for (Constructor<?> candidate : type.getDeclaredConstructors()) {
            if (candidate.isAnnotationPresent(Inject.class)) {
                if (selected != null) {
                    throw new IllegalArgumentException("Multiple @Inject constructors");
                }
                selected = candidate;
            }
        }
        if (selected == null) {
            selected = type.getDeclaredConstructor();
        }

        Class<?>[] parameters = selected.getParameterTypes();
        Object[] arguments;
        if (parameters.length == 0) {
            arguments = new Object[0];
        } else if (parameters.length == 1 && parameters[0] == String.class) {
            arguments = new Object[] {"config"};
        } else {
            throw new IllegalArgumentException("Unsupported constructor signature");
        }
        if (!selected.canAccess(null)) {
            selected.setAccessible(true);
        }
        return type.cast(selected.newInstance(arguments));
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        System.out.println(create(Service.class).name);
        System.out.println(create(Fallback.class).name);
    }
}

final class Service {
    final String name;

    Service() {
        this("no-arg");
    }

    @Inject
    private Service(String name) {
        this.name = name;
    }
}

final class Fallback {
    final String name;

    Fallback() {
        name = "no-arg";
    }
}

Result

config
no-arg

`Service` uses its private `@Inject` constructor even though it also has a no-argument constructor. `Fallback` has no marker and uses its no-argument constructor. The example supplies `"config"` only for the single-`String` signature.

Related lessons

  • Java · Lesson 59 · Advanced · Version: 2

Sources