Item 65. Reflection & Interface

λ¦¬ν”Œλ ‰μ…˜λ³΄λ‹€λŠ” μΈν„°νŽ˜μ΄μŠ€λ₯Ό μ‚¬μš©ν•˜λΌ

λ¦¬ν”Œλ ‰μ…˜ κΈ°λŠ₯을 μ‚¬μš©ν•˜λ©΄ ν”„λ‘œκ·Έλž¨μ—μ„œ μž„μ˜μ˜ ν΄λž˜μŠ€μ— μ ‘κ·Όν•˜μ—¬ κ·Έ 클래슀의 λ©”μ„œλ“œ, ν•„λ“œ, μƒμ„±μžμ— μ ‘κ·Όν•  수 μžˆλ‹€. μ—°κ²°λœ μ‹€μ œ λ©”μ„œλ“œ, ν•„λ“œ, μƒμ„±μžλ₯Ό μ‘°μž‘ν•˜μ—¬ ν•΄λ‹Ή 클래슀의 μΈμŠ€ν„΄μŠ€λ₯Ό 생성, ν•„λ“œ μ ‘κ·Ό, λ©”μ„œλ“œ 호좜 ν•  수 있게 ν•΄μ€€λ‹€. κ²°κ΅­ λ¦¬ν”Œλ ‰μ…˜μ„ μ‚¬μš©ν•˜μ—¬ 컴파일 λ‹Ήμ‹œμ— μ‘΄μž¬ν•˜μ§€ μ•Šλ˜ ν΄λž˜μŠ€λ„ μ΄μš©ν•  수 있게 λ˜λŠ”λ°, λ§Žμ€ 단점이 λ”°λΌμ˜¨λ‹€.

  • 컴파일 νƒ€μž„ νƒ€μž… 검사가 μ£ΌλŠ” 이점이 사라진닀.

  • μ½”λ“œ 양이 λ§Žμ•„μ§€κ³  가독성이 떨어진닀.

  • μ„±λŠ₯ μ €ν•˜κ°€ λ°œμƒν•œλ‹€.

λ•Œλ¬Έμ— μ½”λ“œ 뢄석 λ„κ΅¬λ‚˜ μ˜μ‘΄κ΄€κ³„ μ£Όμž… ν”„λ ˆμž„μ›Œν¬μ²˜λŸΌ μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ˜ λ™μž‘μ„ λ³€κ²½ν•˜λŠ” 데 κΌ­ ν•„μš”ν•œ κ²½μš°κ°€ μ•„λ‹ˆλΌλ©΄ λ¦¬ν”Œλ ‰μ…˜μ€ μ‚¬μš©ν•˜μ§€ μ•ŠλŠ” 것이 μ’‹λ‹€. (μ΄λ§ˆμ €λ„ λ¦¬ν”Œλ ‰μ…˜ μ‚¬μš©μ„ μ€„μ΄κ³ μž ν•˜κ³  μžˆλ‹€.)

μ œν•œλœ ν˜•νƒœμ˜ λ¦¬ν”Œλ ‰μ…˜ μ‚¬μš©

λ¦¬ν”Œλ ‰μ…˜μ„ μ•„μ£Ό μ œν•œλœ ν˜•νƒœλ‘œ μ‚¬μš©ν•˜λ©΄, μ΅œλŒ€ν•œ 단점을 ν”Όν•˜λ©΄μ„œ 이점을 μ·¨ν•  수 있게 λœλ‹€. λ¦¬ν”Œλ ‰μ…˜μ€ μΈμŠ€ν„΄μŠ€ μƒμ„±μ—λ§Œ μ‚¬μš©ν•˜κ³ , μƒμ„±λœ κ°μ²΄λŠ” μΈν„°νŽ˜μ΄μŠ€λ‚˜ μƒμœ„ 클래슀둜 μ°Έμ‘°ν•΄ μ‚¬μš©ν•˜λŠ” 방법이닀.

컴파일 νƒ€μž„μ΄λΌλ„ μ μ ˆν•œ μΈν„°νŽ˜μ΄μŠ€λ‚˜ μƒμœ„ 클래슀λ₯Ό μ΄μš©ν•  수 μžˆλŠ” κ²½μš°κ°€ μžˆλŠ”λ°, λ¦¬ν”Œλ ‰μ…˜μ€ μΈμŠ€ν„΄μŠ€ μƒμ„±μ—λ§Œ μ‚¬μš©ν•˜κ³ , λ§Œλ“  μΈμŠ€ν„΄μŠ€λ₯Ό μΈν„°νŽ˜μ΄μŠ€λ‚˜ μƒμœ„ 클래슀둜 μ°Έμ‘°ν•΄ μ‚¬μš©ν•˜λ©΄ λœλ‹€.

class Example {
    public static void main(String[] args) {
        // 클래슀 이름을 Class 객체둜 λ³€ν™˜
        Class<? extends Set<String>> cl = null;
        try {
            // 비검사 ν˜•λ³€ν™˜
            cl = (Class<? extends Set<String>>) Class.forName("java.util.TreeSet");
        } catch (ClassNotFoundException e) {
            fatalError("클래슀λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.");
        }

        // μƒμ„±μžλ₯Ό μ–»μŒ
        Constructor<? extends Set<String>> cons = null;
        try {
            cons = cl.getDeclaredConstructor();
        } catch (NoSuchMethodException e) {
            fatalError("λ§€κ°œλ³€μˆ˜ μ—†λŠ” μƒμ„±μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.");
        }

        // μ§‘ν•©μ˜ μΈμŠ€ν„΄μŠ€ 생성
        Set<String> s = null;
        try {
            s = cons.newInstance();
        } catch (ReflectiveOperationException e) {
            fatalError("λ¦¬ν”Œλ ‰μ…˜ μ˜ˆμ™Έ λ°œμƒ");
        }

        // μƒμ„±ν•œ 집합 μ‚¬μš©
        String[] a = {"a", "b", "c"};
        s.addAll(Arrays.asList(a).subList(0, a.length));
        System.out.println(s);
    }

    private static void fatalError(String msg) {
        System.err.println(msg);
        System.exit(1);
    }
}

이 방법을 μ‚¬μš©ν•˜λ©΄ λ¦¬ν”Œλ ‰μ…˜μ˜ 단점을 μ΅œλŒ€ν•œ ν”Όν•˜λ©΄μ„œ 이점을 μ·¨ν•  수 있으며, λŒ€λΆ€λΆ„ 경우 λ¦¬ν”Œλ ‰μ…˜ κΈ°λŠ₯은 이 μ •λ„λ‘œλ§Œ μ‚¬μš©ν•˜λŠ” 것이 μ’‹λ‹€.

Last updated