java/코드 리뷰

15. demo1.annotation - (9) MyAnnotationProcessor Demo ( 어노테이션1 )

Astaroth아스 2020. 4. 27. 14:00
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package demo1.annotation;
 
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
 
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
 
// 마크업 어노테이션
// 어노테이션 요소가 정의되어 있지 않는 어노테이션
@Retention(RUNTIME)
@Target(METHOD)
public @interface Test {
    // 어노테이션 요소 정의하는 곳
}
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package demo1.app;
 
import demo1.annotation.Test;
 
public class MyTester {
    
    @Test
    public void test1() {
        System.out.println("test1 실행됨");
    }
    
    public void test2() {
        System.out.println("test2 실행됨");
    }
    
    @Test
    public void test3() {
        System.out.println("test3 실행됨");
    }
    
}
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package demo1.app;
 
import java.lang.reflect.Method;
 
import demo1.annotation.Test;
 
public class MyAnnotationProcessor {
 
    public static void main(String[] args) throws Exception {
 
        MyTester tester = new MyTester();
 
        // 생성된 객체의 설계도정보가 들어있는 Class 객체를 조회
        Class clazz = tester.getClass();
        
        // Class 객체의 설계도 정보 중에서 해당 객체에 선언된 메서드를 전부 조회
        // 메서드 정보가 포함된 Method 객체의 배열이 획득됨
        Method[] methods = clazz.getDeclaredMethods();
        
        // 각 메서드 순회
        for (Method method : methods) {
            // 메서드의 이름 조회
            String methodName = method.getName();
            
            // 메서드에 @Test 어노테이션이 부착되어 있는지 확인
            boolean isPresent = method.isAnnotationPresent(Test.class);
            System.out.println(methodName + ", @Test 부착여부 : " + isPresent);
            
            // @Test 어노테이션이 부착되어 있으면
            if (isPresent) {
                // 해당 객체의 메서드를 실행
                method.invoke(tester);
            }
            
        }
 
    }
}