public class TestClass {
public int a;
public TestClass() {
}
public TestClass(int a) {
this.a = a;
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
TestClass testClass = new TestClass();
Class c = testClass.getClass();
// 선언된 생성자들 출력하기
Constructor[] constructors = c.getDeclaredConstructors();
System.out.println(Arrays.toString(constructors));
// 파라미터가 int인 생성자를 가져오기
Constructor constructor = c.getDeclaredConstructor(int.class);
try {
TestClass testClass2 = (TestClass) constructor.newInstance(10);
System.out.println(testClass2.a);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
[public TestClass(), public TestClass(int)]
10