다른 보존 정책이 내 주석에 어떤 영향을 줍니까?
사람이 명확한 방법으로 간의 실질적인 차이를 설명 할 수 java.lang.annotation.RetentionPolicy
상수 SOURCE
, CLASS
등을 RUNTIME
?
또한 "주석 유지"라는 문구의 의미가 확실하지 않습니다.
RetentionPolicy.SOURCE
: 컴파일 중에 버리십시오. 이 주석은 컴파일이 완료된 후에는 의미가 없으므로 바이트 코드에 기록되지 않습니다.
예 :@Override
,@SuppressWarnings
RetentionPolicy.CLASS
: 수업 중에 버리십시오. 바이트 코드 수준 사후 처리를 수행 할 때 유용합니다. 놀랍게도 이것이 기본값입니다.
RetentionPolicy.RUNTIME
: 버리지 마십시오. 주석은 런타임에 반영 할 수 있어야합니다. 예:@Deprecated
출처 : 이전 URL은 현재
hunter_meta 이고 hunter-meta-2-098036으로 대체되었습니다 . 이 경우에도 페이지 이미지가 업로드됩니다.
이미지 (오른쪽 클릭하고 '새 탭 / 창에서 이미지 열기'를 선택하십시오)
클래스 디 컴파일에 대한 의견에 따르면 다음과 같이 작동합니다.
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
달린 클래스가 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.
'Programming' 카테고리의 다른 글
Visual Studio 2010을 통한 .NET Framework 4.5 대상 지정 (0) | 2020.05.29 |
---|---|
SQL Server에서 사용자와 로그인의 차이점 (0) | 2020.05.29 |
일반 유형 또는 메소드 'System.Nullable'에서 매개 변수 T로 사용하려면 'string'유형은 널 입력 불가능 유형이어야합니다. (0) | 2020.05.29 |
파이썬은 해석되거나 컴파일됩니까, 아니면 둘 다입니까? (0) | 2020.05.29 |
Mockito : 개인 @Autowired 필드에 실제 객체 주입 (0) | 2020.05.29 |