Programming Lang/└ Deep Java

[Java] Retention Policy

haema_dev 2023. 1. 5. 01:34

Retention Policy 란?

컴파일이 되었을 때, 바이트 코드(byte code)로 만들어주는 범위를 지정해주는 정책이다.

이 정책은 enum 으로 등록되어있고, 3가지의 property 를 가진다.

 

여기서 용어 주의 !!

  • byte code : 클래스(.class) 파일. Java Complier 가 OS 관계 없이 실행시킬 수 있도록 변환시킨 코드.
  • binary code : JIT Complier 가 컴퓨터가 읽을 수 있도록 변환시킨 기계코드.
public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}
SOURCE
컴파일 시, 어노테이션은 버린다.
RUNTIME
컴파일 시, 어노테이션이 Class 파일에 기록된다. 하지만 런타임 시에 Virtual Machine 에 메모리가 유지되지 않는다. 이것은 디폴트 행동이다.
CLASS
컴파일 시, Class 파일에 기록되고, 런타임 시, Virtual Machine 에 메모리가 유지된다. 그래서 이것들은 reflection 을 사용하여 읽어오는 것이 가능하다. (reflection 은 다음 기회에...)

 

 

 

그럼 Java 파일과 Class 파일을 비교해보자.

UserInfo.java
@Getter
@AllArgsConstructor
@Table(value = "user_info")
public class UserInfo {
    @Id
    @Column(value = "user_id")
    private String userId;

    @Column(value = "ips")
    private String ips;
}
UserInfo.class
@Table("user_info")
public class UserInfo{
    @Id
    @Column("user_id")
    private String userId;
    @Column("ips")
    private String ips;

    public String getUserId(){
        return this.userId;
    }
    public String getIps(){
        return this.ips;
    }
    public UserInfo(final String userId, final String ips){
        this.userId = userId;
        this.ips = ips;
    }
}

 

source 는 컴파일 시에 어노테이션은 버린다고 했다.

java 파일과 class 파일을 비교해보면 class 파일 쪽은 getter 가 코드로 구현되어있고 @Getter 어노테이션이 없다.

@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
public @interface Getter { . . . }

 @Getter 내부를 살펴부면 RetentionPolicy 가 SOURCE 로 되어있는 것을 확인할 수 있다.

 

runtime 은 컴파일 시에 어노테이션이 class 파일에 기록된다고 했다.

java 파일과 class 파일을 비교해보면 class 파일 쪽에도 @Table 어노테이션이 있다.

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Inherited
public @interface Table { . . . }

 @Table 내부를 살펴보면 RetentionPolicy 가 RUNTIME 으로 되어있는 것을 확인할 수 있다.

 

class 는 컴파일 시에 파일에 기록되고, 런타임 시에 Virtual Machine 에 메모리가 유지된다고 했다.

안타깝지만 위 클래스에서는 사용하지 않기에 코드로 볼 수 있는 방법이 없다.

그렇다면 editor 로 직접 열어서 확인하는 방법도 있다고 한다.

 

 

 

더보기

참고 자료 : JavaDoc

참고 블로그 : https://sas-study.tistory.com/329