programing

서로 다른 보존 정책이 주석에 어떤 영향을 미칩니까?

prostudy 2022. 6. 14. 22:36
반응형

서로 다른 보존 정책이 주석에 어떤 영향을 미칩니까?

이 두 가지 유형의 실제적인 차이점을 명확하게 설명할 수 있는 사람이 있습니까?java.lang.annotation.RetentionPolicy상수SOURCE,CLASS,그리고.RUNTIME?

"주석 보유"라는 문구가 정확히 무슨 뜻인지도 잘 모르겠어요.

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

  • RetentionPolicy.CLASS: 클래스 로드 중에 폐기합니다.바이트 코드 수준의 후처리를 수행할 때 유용합니다.의외로 이것이 기본값입니다.

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

출처: 이전 URL이 비활성화되었습니다. 헌터_스태프hunter-broughter-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;
}

바이트 코드 수준: 사용javap우리가 관찰한 바로는Retention.CLASS주석이 달린 클래스는 Runtime을 가져옵니다.보이지 않는 클래스 속성:

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

하는 동안에Retention.RUNTIME주석은 RuntimeVisible 클래스 속성을 가져옵니다.

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

및 그Runtime.SOURCE주석이 달린.class는 주석을 받지 않습니다.

GitHub에서 플레이할 수 있는 예.

유지 정책:보존 정책은 주석이 폐기되는 시점을 결정합니다.이는 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.
  • CLASS : 주석은 컴파일러에 의해 클래스 파일에 기록되지만 실행 시 VM에 의해 유지될 필요는 없습니다.
  • RUNTIME : 주석은 컴파일러에 의해 클래스 파일에 기록되고 런타임에 VM에 의해 유지되므로 반사적으로 읽힐 수 있습니다.
  • SOURCE : 주석은 컴파일러에 의해 파기됩니다.

오라클 문서

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

반응형