JAVA - 애너테이션

이상원·2023년 3월 28일
0

JAVA

목록 보기
6/6

애너테이션

주석 처럼 프로그래밍 언어에 영향을 미치지 않으면서 다른 프로그램에게 유용한 정보를 제공할 수 있는 장점이 있는 것. 다른 프로그램을 위한 정보를 미리 약속된 형식으로 소스 코드 안에 포함 시킨 것

애너테이션 종류

  • 표준 애너테이션

  • 메타 애너테이션

메타 애너테이션

메타 애너테이션은 "애너테이션을 위한 애너테이션" 즉, 애너테이션에 붙이는 애너테이션을 말한다. 이것은 적용 대상(target) 이나 유지 기간(retention)등을 지정하는 데 사용된다.

@Target

애너테이셔닝 적용가능한 대상을 지정하는 데 사용 된다. 즉, 이 애너테이션에 적용할 수 있는 대상을 @Target으로 지정하는 것이다. 여러 개의 값은 괄호로 지정


import static java.lang.annotation.ElementType.*;

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    /**
     * The set of warnings that are to be suppressed by the compiler in the
     * annotated element.  Duplicate names are permitted.  The second and
     * successive occurrences of a name are ignored.  The presence of
     * unrecognized warning names is <i>not</i> an error: Compilers must
     * ignore any warning names they do not recognize.  They are, however,
     * free to emit a warning if an annotation contains an unrecognized
     * warning name.
     *
     * <p> The string {@code "unchecked"} is used to suppress
     * unchecked warnings. Compiler vendors should document the
     * additional warning names they support in conjunction with this
     * annotation type. They are encouraged to cooperate to ensure
     * that the same names work across multiple compilers.
     * @return the set of warnings to be suppressed
     */
    String[] value();
}

@Retention

애너테이션이 유지(retention)되는 기간을 지정하는 데 사용된다. 애너테이션의 유지 정책(retention policy)은 다음과 같다.

  • 컴파일러에 의해 사용되는 애너테이션의 유지 정책은 SOURCE 이다.
    컴파일러를 직접 작성할 것이 아니면 이 유지 정책은 필요없다.
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
  • 유지 정책을 RUNTIME으로 하면 실행 시에 리플랙션을 통해 클래스 파일에 저장된 애너테이션의 정보를 읽어서 처리할 수 있다.

  • 유지 정책 CLASS는 컴파일러가 애너테이션의 정보를 클래스 파일에 저장할 수 있게 하지만 클래스 파일이 JVM에 의해서 로딩될 때 애너테이션 정보가 무시되므로 잘 사용 X

@Documented , @Inherited

  • javadoc으로 작성한 문서에 포함시키려면 @Documented 를 붙인다.
  @Documented
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.TYPE)
  public @interface FunctionalInterface {}
  • 애너테이션을 자손 클래스에 상속하고자 할 때는, @Inherited를 붙인다.

@Repeatable

  • 반복해서 붙일 수 있는 애너테이션을 정의할 때 사용한다.

  • @Repeatable이 붙은 애너테이션은 반복해서 붙일 수 있다.

profile
개발하는 코린이

0개의 댓글