Java : Constructor (reflection) with Examples

Constructor (Java SE 18 & JDK 18) API Examples.
You will find code examples on most Constructor methods.


Summary

Constructor provides information about, and access to, a single constructor for a class.

Class diagram

public class AccessTest {
    private final int num;

    private AccessTest(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }
}
//new AccessTest(123); // Compile error.

final var cls = AccessTest.class;

final var cons = cls.getDeclaredConstructor(int.class);
System.out.println(cons); // private AccessTest(int)

System.out.println(cons.canAccess(null)); // false

//final var obj = cons.newInstance(123); // IllegalAccessException

System.out.println(cons.trySetAccessible()); // true
System.out.println(cons.canAccess(null)); // true

final var obj = cons.newInstance(123);
System.out.println(obj.getNum()); // 123

Fields declared in Member

DECLARED, PUBLIC

Please see the link below.

Methods

boolean equals (Object obj)

Compares this Constructor against the specified object.

public class Foo {
    public Foo() {
    }

    public Foo(int num) {
    }
}
final var foo1 = new Foo();
final var foo2 = new Foo();

final var cons1 = foo1.getClass().getDeclaredConstructor();
final var cons2 = foo2.getClass().getDeclaredConstructor();

System.out.println(cons1.equals(cons2)); // true

final var cons3 = foo1.getClass().getDeclaredConstructor(int.class);

System.out.println(cons3.equals(cons1)); // false

AnnotatedType getAnnotatedReceiverType ()

Returns an AnnotatedType object that represents the use of a type to specify the receiver type of the method/constructor represented by this Executable object.

public class Foo {
    public Foo() {
    }

    public class Bar {
        public Bar() {
        }
    }
}
final var cls = Foo.class;

final var cons = cls.getDeclaredConstructor();
System.out.println(cons); // public Foo()

final var type = cons.getAnnotatedReceiverType();
System.out.println(type); // null
final var cls = Foo.Bar.class;

final var cons = cls.getDeclaredConstructor(Foo.class);
System.out.println(cons); // public Foo$Bar(Foo)

final var type = cons.getAnnotatedReceiverType();
System.out.println(type); // Foo

AnnotatedType getAnnotatedReturnType ()

Returns an AnnotatedType object that represents the use of a type to specify the return type of the method/constructor represented by this Executable.

public class Foo {
    public Foo() {
    }
}
final var cls = Foo.class;

final var cons = cls.getDeclaredConstructor();
System.out.println(cons); // public Foo()

final var type = cons.getAnnotatedReturnType();
System.out.println(type); // Foo

<T extends Annotation> T getAnnotation (Class<T> annotationClass)

Returns this element's annotation for the specified type if such an annotation is present, else null.

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

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

public class A {

    @Foo
    public A() {
    }

    @Bar
    public A(int num) {
    }
}
final var cons = A.class.getDeclaredConstructor();

final var ret1 = cons.getAnnotation(Foo.class);
System.out.println(ret1); // @Foo()

final var ret2 = cons.getAnnotation(Bar.class);
System.out.println(ret2); // null
final var cons = A.class.getDeclaredConstructor(int.class);

final var ret1 = cons.getAnnotation(Foo.class);
System.out.println(ret1); // null

final var ret2 = cons.getAnnotation(Bar.class);
System.out.println(ret2); // @Bar()

Annotation[] getDeclaredAnnotations ()

Returns annotations that are directly present on this element.

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

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

public class A {
    @Foo
    @Bar
    public A() {
    }
}
final var cons = A.class.getDeclaredConstructor();

System.out.println("-- annotations --");
for (final var a : cons.getDeclaredAnnotations()) {
    System.out.println(a);
}

// Result
// ↓
//-- annotations --
//@Foo()
//@Bar()

Class<T> getDeclaringClass ()

Returns the Class object representing the class that declares the constructor represented by this object.

public class Foo {
    public Foo() {
    }
}
final var cls = Foo.class;

final var cons = cls.getDeclaredConstructor();
System.out.println(cons); // public Foo()

final var ret = cons.getDeclaringClass();
System.out.println(ret); // class Foo
System.out.println(cls.equals(ret)); // true

Class<?>[] getExceptionTypes ()

Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying executable represented by this object.

public class Foo<T extends Exception> {
    public Foo() throws T, IOException {
    }
}
final var cls = Foo.class;

final var cons = cls.getDeclaredConstructor();
System.out.println(cons);

System.out.println("-- getExceptionTypes --");
for (final var type : cons.getExceptionTypes()) {
    System.out.println(type);
}

System.out.println("-- getGenericExceptionTypes --");
for (final var type : cons.getGenericExceptionTypes()) {
    System.out.println(type);
}

// Result
// ↓
//public Foo() throws java.lang.Exception,java.io.IOException
//-- getExceptionTypes --
//class java.lang.Exception
//class java.io.IOException
//-- getGenericExceptionTypes --
//T
//class java.io.IOException

Type[] getGenericExceptionTypes ()

Returns an array of Type objects that represent the exceptions declared to be thrown by this executable object.

Please see getExceptionTypes().

Type[] getGenericParameterTypes ()

Returns an array of Type objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

public class Foo<T> {
    public Foo(int num, T value) {
    }
}
final var cls = Foo.class;

final var cons = cls.getDeclaredConstructor(int.class, Object.class);
System.out.println(cons);

System.out.println("-- getParameterTypes --");
for (final var type : cons.getParameterTypes()) {
    System.out.println(type);
}

System.out.println("-- getGenericParameterTypes --");
for (final var type : cons.getGenericParameterTypes()) {
    System.out.println(type);
}

// Result
// ↓
//public Foo(int,java.lang.Object)
//-- getParameterTypes --
//int
//class java.lang.Object
//-- getGenericParameterTypes --
//int
//T

int getModifiers ()

Returns the Java language modifiers for the executable represented by this object.

public class Foo {
    public Foo() {
    }

    protected Foo(int num) {
    }

    private Foo(String str) {
    }
}
final var cls = Foo.class;

for (final var cons : cls.getDeclaredConstructors()) {
    final var mod = cons.getModifiers();
    System.out.println(cons + " : mod = " + mod);
    System.out.println("  isPublic : " + Modifier.isPublic(mod));
    System.out.println("  isProtected : " + Modifier.isProtected(mod));
    System.out.println("  isPrivate : " + Modifier.isPrivate(mod));
}

// Result
// ↓
//public Foo() : mod = 1
//  isPublic : true
//  isProtected : false
//  isPrivate : false
//protected Foo(int) : mod = 4
//  isPublic : false
//  isProtected : true
//  isPrivate : false
//private Foo(java.lang.String) : mod = 2
//  isPublic : false
//  isProtected : false
//  isPrivate : true

String getName ()

Returns the name of this constructor, as a string.

public class Foo {
    public Foo() {
    }
}
final var cls = Foo.class;

final var cons = cls.getDeclaredConstructor();
System.out.println(cons); // public Foo()
System.out.println(cons.getName()); // Foo

Annotation[][] getParameterAnnotations ()

Returns an array of arrays of Annotations that represent the annotations on the formal parameters, in declaration order, of the Executable represented by this object.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Foo {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Bar {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Baz {
}

public class A {
    public A(@Foo @Bar int num, @Baz String str) {
    }
}
final var cons = A.class.getDeclaredConstructor(int.class, String.class);
System.out.println(cons);

System.out.println("-- annotations --");
for (final var a : cons.getParameterAnnotations()) {
    System.out.println(Arrays.toString(a));
}

// Result
// ↓
//public A(int,java.lang.String)
//-- annotations --
//[@Foo(), @Bar()]
//[@Baz()]

int getParameterCount ()

Returns the number of formal parameters (whether explicitly declared or implicitly declared or neither) for the executable represented by this object.

public class Foo {
    public Foo() {
    }

    public Foo(int num) {
    }

    public Foo(int num, String str) {
    }
}
final var cls = Foo.class;

final var cons1 = cls.getDeclaredConstructor();
System.out.println(cons1); // public Foo()
System.out.println(cons1.getParameterCount()); // 0

final var cons2 = cls.getDeclaredConstructor(int.class);
System.out.println(cons2); // public Foo(int)
System.out.println(cons2.getParameterCount()); // 1

final var cons3 = cls.getDeclaredConstructor(int.class, String.class);
System.out.println(cons3); // public Foo(int,java.lang.String)
System.out.println(cons3.getParameterCount()); // 2

Class<?>[] getParameterTypes ()

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

Please see getGenericParameterTypes().

TypeVariable<Constructor<T>>[] getTypeParameters ()

Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.

public class Foo {
    public <T, U> Foo(T t, U u) {
    }
}
final var cons = Foo.class.getDeclaredConstructor(Object.class, Object.class);
System.out.println(cons);

System.out.println("-- parameters --");
for (final var param : cons.getTypeParameters()) {
    System.out.println(param);
}

// Result
// ↓
//public Foo(java.lang.Object,java.lang.Object)
//-- parameters --
//T
//U

int hashCode ()

Returns a hashcode for this Constructor.

public class Foo {
    public Foo() {
    }

    public Foo(int num) {
    }
}

public class Bar {
    public Bar() {
    }
}
final var ret1 = Foo.class.getDeclaredConstructor().hashCode();
System.out.println(ret1); // -1315575833

final var ret2 = Foo.class.getDeclaredConstructor(int.class).hashCode();
System.out.println(ret2); // -1315575833

final var ret3 = Bar.class.getDeclaredConstructor().hashCode();
System.out.println(ret3); // -1315580108

boolean isSynthetic ()

Returns true if this executable is a synthetic construct; returns false otherwise.

public class Foo {
    public Foo() {
    }
}
final var cls = Foo.class;

final var cons = cls.getDeclaredConstructor();
System.out.println(cons); // public Foo()
System.out.println(cons.isSynthetic()); // false

boolean isVarArgs ()

Returns true if this executable was declared to take a variable number of arguments; returns false otherwise.

public class Foo {
    public Foo(int num) {
    }

    public Foo(int num, String... args) {
    }
}
final var cons = Foo.class.getDeclaredConstructor(int.class);
System.out.println(cons); // public Foo(int)
System.out.println(cons.isVarArgs()); // false
final var cons = Foo.class.getDeclaredConstructor(int.class, String[].class);
System.out.println(cons); // public Foo(int,java.lang.String[])
System.out.println(cons.isVarArgs()); // true

T newInstance (Object... initargs)

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

public class AccessTest2 {
    private final int num;
    private final String str;

    public AccessTest2(int num) {
        this.num = num;
        this.str = "abc";
    }

    private AccessTest2(String str) {
        this.num = 0;
        this.str = str;
    }

    public int getNum() {
        return num;
    }

    public String getStr() {
        return str;
    }
}
final var cls = AccessTest2.class;

final var cons = cls.getDeclaredConstructor(int.class);
System.out.println(cons); // public AccessTest2(int)

System.out.println(cons.canAccess(null)); // true

final var obj = cons.newInstance(123);
System.out.println(obj.getNum()); // 123
System.out.println(obj.getStr()); // abc
final var cls = AccessTest2.class;

final var cons = cls.getDeclaredConstructor(String.class);
System.out.println(cons); // private AccessTest2(java.lang.String)

System.out.println(cons.canAccess(null)); // false

// final var obj = cons.newInstance("XYZ"); // IllegalAccessException

System.out.println(cons.trySetAccessible()); // true
System.out.println(cons.canAccess(null)); // true

final var obj = cons.newInstance("XYZ");
System.out.println(obj.getNum()); // 0
System.out.println(obj.getStr()); // XYZ

void setAccessible (boolean flag)

Set the accessible flag for this reflected object to the indicated boolean value.

public class AccessTest {
    private final int num;

    private AccessTest(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }
}
final var cons = AccessTest.class.getDeclaredConstructor(int.class);

System.out.println(cons.canAccess(null)); // false

cons.setAccessible(true);
System.out.println(cons.canAccess(null)); // true

cons.setAccessible(false);
System.out.println(cons.canAccess(null)); // false

String toGenericString ()

Returns a string describing this Constructor, including type parameters.

public class Foo<T> {
    public Foo(int num) {
    }

    public Foo(T value) {
    }
}
final var cons = Foo.class.getDeclaredConstructor(int.class);

final var ret1 = cons.toGenericString();
System.out.println(ret1); // public Foo(int)

final var ret2 = cons.toString();
System.out.println(ret2); // public Foo(int)
final var cons = Foo.class.getDeclaredConstructor(Object.class);

final var ret1 = cons.toGenericString();
System.out.println(ret1); // public Foo(T)

final var ret2 = cons.toString();
System.out.println(ret2); // public Foo(java.lang.Object)

String toString ()

Returns a string describing this Constructor.

Please see toGenericString().

Methods declared in Executable

getAnnotatedExceptionTypes, getAnnotatedParameterTypes, getAnnotationsByType, getParameters

Please see the link below.

Methods declared in AccessibleObject

canAccess, getAnnotations, getDeclaredAnnotation, getDeclaredAnnotationsByType, isAccessible, isAnnotationPresent, setAccessible, trySetAccessible

Please see the link below.

Methods declared in AnnotatedElement

getAnnotations, getDeclaredAnnotation, getDeclaredAnnotationsByType, isAnnotationPresent

Please see the link below.


Related posts

To top of page