Java

[Java] 리플렉션 - 2 (어노테이션)

MbyM 2020. 7. 25. 14:37

 

- 참고 : 인프런 >> 더 자바, 코드를 조작하는 다양한 방법, (백기선 강의)

 

Annotation

  • @Retention - 어노테이션의 범위로 어떤 시점까지 어노테이션이 영향을 미치는지 결정
    • SOURCE
    • CLASS (default, Class 파일까지만 로드 됨)
    • RUNTIME
  • @Target -  어노테이션 적용할 위치
    • FIELD, METHOD, PARAMETER, CONSTRUCTOR, 등...
  • @Inherited - 자식 클래스가 어노테이션을 상속

 

Class Reflction API, 어노테이션

 

  • getAnnotations - 상속받은 (@Inherit) 어노테이션까지 조회
  • getDeclaredAnnotations - 자기 자신에만 붙어있는 어노테이션 조회

 

Test

 

[MyAnnotation]

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.FIELD})
public @interface MyAnnotation {

	String name() default "name";
    
}

 

[MyBook]

@NoArgsConstructor
@MyAnnotation(name = "MyBook")
public class Mybook extends Book implements MyInterface{
}

 

[어노테이션 조회 Test]

@Test
public void test_어노테이션_조회(){
    printText("getAnnotations");
    Arrays.stream(Mybook.class.getAnnotations()).forEach(System.out::println);
    finish();
}

 

>> 결과

===========[getAnnotations]===========
@com.example.test.reflection.MyAnnotation(name="MyBook")
============================================