자바 공부/[자바] 기본 공부

[자바 공부 4일차] 어노테이션

햅2024 2024. 11. 11. 18:25

어노테이션이란 자바 소스 코드에 추가하여 사용할 수 있는 메타데이터의 일종이다.

 

Count100 이라는 어노테이션을 만들어보자.

package JavaUtil.exam;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME) //실행시 감지
public @interface Count100 {

}

 

@Retention(RetentionPolicy.RUNTIME) 이란 코드를 통해 프로그램이 실행할 때 해당 어노테이션이 있는지 감지한다.

 

 

@Count100 을 클래스에 전역으로 선언하여 어노테이션을 선언한다.

package JavaUtil.exam;

public class MyHello {
	@Count100
	public void hello()
	{
		System.out.println("hello");
		
	}
}

 

 

Main 함수에 해당 클래스를 생성하여 실행해보자.

package JavaUtil.exam;

import java.lang.reflect.Method;

public class MyHelloExam {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyHello hello = new MyHello();
		
		try {
			Method method = hello.getClass().getDeclaredMethod("hello");
			
			//count100 어노테이션을 적용하고 있는가?
			if(method.isAnnotationPresent(Count100.class))
			{
				for(int i=0;i<100;i++) {
					hello.hello();
				}
			}
			else {
				hello.hello();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		//getClass() : 해당 인스턴스를 만들 떄 사용한 class의 정보를 return
		//getDeclaredMethod : hello라는 이름의 method의 정보를 구해라
		
	}

}

 

 

어노테이션 적용 여부 확인은 Method 메소드를 이용해야 하기 때문에 

import java.lang.reflect.Method;

를 임포트 해준다.

 

어노테이션 적용을 알아보기 위해선 try catch 문을 사용해야 한다.

try {
    Method method = hello.getClass().getDeclaredMethod("hello");
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

 

getClass() : 해당 인스턴스를 만들 때 사용한 class의 정보를 return
getDeclaredMethod : hello라는 이름의 method의 정보를 구해라

 

try {
    Method method = hello.getClass().getDeclaredMethod("hello");

    //count100 어노테이션을 적용하고 있는가?
    if(method.isAnnotationPresent(Count100.class))
    {
        for(int i=0;i<100;i++) {
            hello.hello();
        }
    }
    else {

    }
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

method에 Count100 클래스라는 어노테이션을 적용했다면 hello를 총 100번 출력한다.

 

100번이 출력되는 것을 볼 수 있다.