gmarket-ssb / book-study

4 stars 2 forks source link

item40 #3

Open wrallee opened 2 years ago

wrallee commented 2 years ago

Override 어노테이션을 생략해도 동작하는 이유? Override 어노테이션도 어노테이션 프로세서가 처리하는건가요?

dev-hajs commented 2 years ago

@Override 어노테이션을 생략해도 동작하는 이유를 간단하게 생각해보았습니다.
예를들어 새로 만든 객체에 .toString() 메소드를 재정의하지 않고 호출하면 Object 의 .toString() 메소드가 찍히는 것과 비슷한 맥락이 아닐까요? 🧐

더불어 @Override 어노테이션은 까보면 아무것도 하는게 없는 선언형 어노테이션 입니다.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}


결국 @Override 어노테이션은 언어의 조각(규약)이 아닌, 단순히 컴파일러에게 hint 를 주는 어노테이션임을 알 수 있습니다.
그래서 (이 어노테이션이 선언되어) hint 를 받은 컴파일러는 메소드를 "validate" 하여 경고를 줄 수 있게 되는 것이죠 !

비슷한 맥락으로 함수형 인터페이스임을 명시하는 @FunctionalInterface 어노테이션 주석에는 이런 문구가 있습니다.

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

간단하게 해석하자면, 컴파일러는 이 어노테이션이 없어도 있는 것 처럼 동작한다 고 합니다.
@Override 도 결국 조건에 부합(same name, same return type, same args format..) 하면 컴파일러가 있는 것 처럼 동작하는게 아닐까요? 🧐 다른 분들의 의견도 궁금하네요...

jaesay commented 2 years ago

참고

Command-line options and environment variables also control how javac performs various tasks:

⇒ 자바 컴파일러가 애너테이션 처리

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

The annotation processor generally uses the Reflection API to inspect the elements being compiled and may simply run checks on them, modify them, or generate new code to be compiled. @Override is an example of the first; it uses the Reflection API to make sure it can find a match for the method signature in one of the superclasses and uses the Messager to cause a compile error if it can't.

@Override애너테이션의 리텐션폴리시는 소스코드까지만 유지(컴파일러에 의해 버려짐)

⇒ 애너테이션 프로세서를 통해 체크, 수정, 새로운 것들을 만들 수 있음

⇒ 슈퍼클래스와 같은 method signature가 있는지 체크하고 메신저를 사용해서 컴파일 에러를 알린다.

dev-hajs commented 2 years ago

리뷰 완료