Java : Constructor (リフレクション) - API使用例
Constructor (Java SE 18 & JDK 18) の使用例まとめです。
 だいたいのメソッドを網羅済みです。
 API仕様のおともにどうぞ。
概要
Constructorは、クラスの単一コンストラクタについての情報と単一コンストラクタへのアクセスを提供します。
Constructor を使うと、例えば private なコンストラクタからオブジェクトを生成できるようになります。
public class AccessTest {
    private final int num;
    private AccessTest(int num) {
        this.num = num;
    }
    public int getNum() {
        return num;
    }
}
//new AccessTest(123); // コンパイルエラー
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
Memberで宣言されたフィールド
DECLARED, PUBLIC
「Java API 使用例 : Member」をご参照ください。
メソッド
boolean equals (Object obj)
このConstructorを指定されたオブジェクトと比較します。
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 ()
このExecutableオブジェクトによって表されるメソッド/コンストラクタのレシーバ型を指定する型の使用を表すAnnotatedTypeオブジェクトを返します。
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 ()
このExecutableによって表されるメソッドまたはコンストラクタの戻り型を指定する型の使用を表すAnnotatedTypeオブジェクトを返します。
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)
存在する場合は、この要素の指定された型の注釈を返し、そうでない場合は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 ()
この要素に直接存在する注釈を返します。
@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);
}
// 結果
// ↓
//-- annotations --
//@Foo()
//@Bar()
Class<T> getDeclaringClass ()
このオブジェクトが表すコンストラクタを宣言するクラスを表すClassオブジェクトを返します。
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 ()
このオブジェクトで表される基礎となる実行可能ファイルによってスローされるように宣言されている例外の型を表すClassオブジェクトの配列を返します。
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);
}
// 結果
// ↓
//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 ()
このexecutableオブジェクトによってスローされることが宣言されている例外を表すTypeオブジェクトの配列を返します。
このメソッドの使用例は、getExceptionTypes() にまとめて記載しました。
 そちらのAPI使用例をご参照ください。
Type[] getGenericParameterTypes ()
このオブジェクトによって表される実行可能要素の仮パラメータ型を宣言順で表すTypeオブジェクトの配列を返します。
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);
}
// 結果
// ↓
//public Foo(int,java.lang.Object)
//-- getParameterTypes --
//int
//class java.lang.Object
//-- getGenericParameterTypes --
//int
//T
int getModifiers ()
このオブジェクトによって表される実行可能要素のJava言語修飾子を返します。
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));
}
// 結果
// ↓
//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 ()
このコンストラクタの名前を文字列として返します。
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 ()
このオブジェクトによって表されるExecutableの仮パラメータの注釈を表すAnnotationの配列の配列を、宣言順に返します。
@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));
}
// 結果
// ↓
//public A(int,java.lang.String)
//-- annotations --
//[@Foo(), @Bar()]
//[@Baz()]
int getParameterCount ()
このオブジェクトによって表される実行可能要素の仮パラメータ(明示的に宣言されているか、暗黙的に宣言されているか、そのいずれでもないかに関係なく)の数を返します。
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 ()
このオブジェクトによって表される実行可能ファイルの仮パラメータ型を宣言順で表すClassオブジェクトの配列を返します。
このメソッドの使用例は、getGenericParameterTypes() にまとめて記載しました。
 そちらのAPI使用例をご参照ください。
TypeVariable<Constructor<T>>[] getTypeParameters ()
GenericDeclarationオブジェクトによって表されるジェネリック宣言で宣言された型変数を表すTypeVariableオブジェクトの配列を宣言順に返します。
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);
}
// 結果
// ↓
//public Foo(java.lang.Object,java.lang.Object)
//-- parameters --
//T
//U
int hashCode ()
この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 ()
この実行可能要素が合成構造である場合はtrueを返し、そうでない場合はfalseを返します。
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 ()
この実行可能要素が可変数の引数を取るように宣言されていた場合はtrueを返し、そうでない場合はfalseを返します。
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)
指定された初期化パラメータで、このコンストラクタの宣言クラスの新しいインスタンスを作成および初期化する場合は、このConstructorオブジェクトによって表されるコンストラクタを使用します。
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)
このリフレクトされたオブジェクトのaccessibleフラグを、指定されたブール値に設定します。
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 ()
型パラメータを含む、このConstructorを記述する文字列を返します。
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 ()
このConstructorを記述する文字列を返します。
このメソッドの使用例は、toGenericString() にまとめて記載しました。
 そちらのAPI使用例をご参照ください。
Executableで宣言されたメソッド
getAnnotatedExceptionTypes, getAnnotatedParameterTypes, getAnnotationsByType, getParameters
「Java API 使用例 : Executable」をご参照ください。
AccessibleObjectで宣言されたメソッド
canAccess, getAnnotations, getDeclaredAnnotation, getDeclaredAnnotationsByType, isAccessible, isAnnotationPresent, setAccessible, trySetAccessible
「Java API 使用例 : AccessibleObject」をご参照ください。
AnnotatedElementで宣言されたメソッド
getAnnotations, getDeclaredAnnotation, getDeclaredAnnotationsByType, isAnnotationPresent
「Java API 使用例 : AnnotatedElement」をご参照ください。




