Programming Practice/Java

Annotation Type 사용

효돌프 2015. 3. 29. 11:20

1. 작성

 1) 생성

   - eclipse : New - Annotation

 2) 변수 구성

   - 일반변수();

 3) Annotation 구성

   - class 또는 field 에 설정된 annotation 객체를 사용하기 위해서는

     @Retention(RetentionPolicy.RUNTIME)

   -

 사용 대상

 annotation 

 class

 @Target(ElementType.TYPE)

 field

 @Target(ElementType.FIELD)

 

2. class에 사용

 1) 사용

   - class 의 위에 @annotationtype명(변수1=값1, 변수2=값2) 로 설정한다.

 2) 목적

  ㄱ. comments 강제

    - Annotation type은 기본적으로 주석으로 작성했던 class 의 comments를 대체한다.

    - Class 에서 Annotation type을 호출했을 때, 호출한 Annotation type의 변수를 지정하지 않을 경우 compile error 가 발생한다.

    cf. annotation 내 변수에 default 값이 있는 경우, class 에서 호출한 Annotation type 의 변수를 지정하지 않아도 된다.

 

  ㄴ. class 분류

   - 아래의 방식으로 class의 annotation 변수의 값을 다른 곳에서 사용 가능

 1) class -> Object

 2) Object -> Class<?>

 3) class 에 설정된 annotation 가져오기

 4) annotation.변수() 형태로 변수값 가져오기

 - annotation 구성시 @Retention(RetentionPolicy.RUNTIME)으로 설정해야 한다.


3. field에 사용

 1) 사용, 목적은 class에 사용과 거의 동일 (field에 사용은 field를 분류하기 위함)

   field 분류는 아래와 같이 사용한다.

    - annotation 설정

   - 사용