Programming

다른 보존 정책이 내 주석에 어떤 영향을 줍니까?

procodes 2020. 5. 29. 23:30
반응형

다른 보존 정책이 내 주석에 어떤 영향을 줍니까?


사람이 명확한 방법으로 간의 실질적인 차이를 설명 할 수 java.lang.annotation.RetentionPolicy상수 SOURCE, CLASS등을 RUNTIME?

또한 "주석 유지"라는 문구의 의미가 확실하지 않습니다.


  • RetentionPolicy.SOURCE: 컴파일 중에 버리십시오. 이 주석은 컴파일이 완료된 후에는 의미가 없으므로 바이트 코드에 기록되지 않습니다.
    예 : @Override,@SuppressWarnings

  • RetentionPolicy.CLASS: 수업 중에 버리십시오. 바이트 코드 수준 사후 처리를 수행 할 때 유용합니다. 놀랍게도 이것이 기본값입니다.

  • RetentionPolicy.RUNTIME: 버리지 마십시오. 주석은 런타임에 반영 할 수 있어야합니다. 예:@Deprecated

출처 : 이전 URL은 현재 hunter_meta 이고 hunter-meta-2-098036으로 대체되었습니다 . 이 경우에도 페이지 이미지가 업로드됩니다.

이미지 (오른쪽 클릭하고 '새 탭 / 창에서 이미지 열기'를 선택하십시오) Oracle 웹 사이트 스크린 샷


클래스 디 컴파일에 대한 의견에 따르면 다음과 같이 작동합니다.

  • RetentionPolicy.SOURCE: 디 컴파일 된 클래스에 나타나지 않습니다

  • RetentionPolicy.CLASS: 디 컴파일 된 클래스에 나타나지만 다음을 반영하여 런타임에 검사 할 수 없습니다. getAnnotations()

  • RetentionPolicy.RUNTIME: 디 컴파일 된 클래스에 나타나고 다음을 반영하여 런타임에 검사 할 수 있습니다. getAnnotations()


최소 실행 가능 예

언어 수준 :

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

@Retention(RetentionPolicy.SOURCE)
@interface RetentionSource {}

@Retention(RetentionPolicy.CLASS)
@interface RetentionClass {}

@Retention(RetentionPolicy.RUNTIME)
@interface RetentionRuntime {}

public static void main(String[] args) {
    @RetentionSource
    class B {}
    assert B.class.getAnnotations().length == 0;

    @RetentionClass
    class C {}
    assert C.class.getAnnotations().length == 0;

    @RetentionRuntime
    class D {}
    assert D.class.getAnnotations().length == 1;
}

바이트 코드 레벨 : 주석 javapRetention.CLASS달린 클래스가 RuntimeInvisible 클래스 속성을 얻는 것을 관찰했습니다 .

#14 = Utf8               LRetentionClass;
[...]
RuntimeInvisibleAnnotations:
  0: #14()

반면 Retention.RUNTIME주석은 도착 RuntimeVisible 클래스 속성을 :

#14 = Utf8               LRetentionRuntime;
[...]
RuntimeVisibleAnnotations:
  0: #14()

그리고 Runtime.SOURCE주석 .class모든 주석을하지 않습니다.

함께 플레이 할 수있는 GitHub의 예 .


RetentionPolicy.SOURCE: 주석은 프로그램의 소스 코드에서 사용할 수 있으며, .class 파일이나 런타임에서 사용할 수 없습니다. 컴파일러에서 사용합니다.
RetentionPolicy.CLASS: 주석은 .class 파일에 있지만 런타임에는 사용할 수 없습니다. ASM과 같은 바이트 코드 조작 도구에서 사용하여 수정을 수행합니다
RetentionPolicy.RUNTIME. 주석은 .class 파일 및 런타임에서 Java 리플렉션을 통한 검사를 위해 사용할 수 있습니다 getAnnotations().


보존 정책 : 보존 정책은 주석을 폐기 할 시점을 결정합니다. Java의 내장 주석을 사용하여 지정됩니다. @Retention[정보]

1.SOURCE: annotation retained only in the source file and is discarded
          during compilation.
2.CLASS: annotation stored in the .class file during compilation,
         not available in the run time.
3.RUNTIME: annotation stored in the .class file and available in the run time.

참고 URL : https://stackoverflow.com/questions/3107970/how-do-different-retention-policies-affect-my-annotations

반응형