어노테이션을 위한 어노테이션
@Target : 어노테이션을 정의할 때 적용대상을 지정하는데 사용한다.
@Retention : 어노테이션이 유지되는 기간을 지정하는데 사용한다.
@Documented : javadoc으로 작성한 문서에 포함시키려면 해당 어노테이션을 붙인다.
@Inherited : 어노테이션을 자손 클래스에 상속하고자 할 때 사용한다.
@Repetable : 반복해서 붙일 수 있는 어노테이션을 정의할 때 사용한다.
사용자가 직접 작성하는 어노테이션을 Custom 어노테이션이라고 말합니다.
커스텀 어노테이션 생성하는 방법 - 예제
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Count100 {
}
public class MyHello {
@Count100
public void hello(){
System.out.println("hello");
}
}
import java.lang.reflect.Method;
public class MyHelloExam {
public static void main(String[] args) {
MyHello hello = new MyHello();
try{
Method method = hello.getClass().getDeclaredMethod("hello"); // 해당 클래스에 선언된 hello 로 선언된 메서드를 받아온다.
if(method.isAnnotationPresent(Count100.class)){ // 해당 메서드에 Count100 이라는 어노테이션이 설정되어 있다면
for(int i = 0; i < 100; i++){
hello.hello();
}
}else{
hello.hello();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}