Skip to content

Latest commit

 

History

History
54 lines (44 loc) · 1.32 KB

2_가져온 생성자로 인스턴스 생성.md

File metadata and controls

54 lines (44 loc) · 1.32 KB

가져온 생성자로 인스턴스 생성하기

1. Test 클래스 생성

public class TestClass {
    public int a;
    public TestClass() {
    }

    public TestClass(int a) {
        this.a = a;
    }
}

2. main

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);
        }


    }
}

3. 실행 결과

[public TestClass(), public TestClass(int)]
10