Annotation Processor

22·2023년 12월 7일

Java

목록 보기
1/3
  • Annotation Processor 는 소스 코드를 분석하여 특정 어노테이션이 적용된 요소들을 찾고, 이에 대한 추가적인 코드생성이나 변경을 수행한다.
    덕분에 개발자는 반복적이거나 일상적인 작업을 자동화하고, 코드의 가독성을 향상시키며, 코드의 일관성을 유지할 수 있다.

  • Processor 인터페이스를 상속받아 구현한다. process 메서드를 구현해야한다.

  • QueryDSL, Json, Lombok 등 여러 기술들에서 사용된다.

예를 들어 lombok의 @getter 를 사용하면 getXXX 메서드는 java 파일에 생기는 것이 아닌 클래스 파일에 있다.

text @getter 어노테이션을 사용한 Person 클래스의 class file

java 의 컴파일 단계는 3가지 단계로 진행된다.

This process is handled by the JavaCompiler class.

  1. All the source files specified on the command line are read, parsed into syntax trees, and then all externally visible definitions are entered into the compiler's symbol tables.
  2. All appropriate annotation processors are called. If any annotation processors generate any new source or class files, the compilation is restarted, until no new files are created.
  3. Finally, the syntax trees created by the parser are analyzed and translated into class files. During the course of the analysis, references to additional classes may be found. The compiler will check the source and class path for these classes; if they are found on the source path, those files will be compiled as well, although they will not be subject to annotation processing.

Annotation Processor 는 위 사진에서 2단계에서 진행된다. 컴파일러는 java 코드를 ast 트리 형태로 파싱하여 구문 분석을 한다. 그리고 그 트리를 기반으로 class file 을 생성하는데 2단계에서 코드를 추가한다.

2단계에서는 적절한 annotation processor 들이 호출된다. 만약 annotation processor 중 어떤 것이라도 새로운 소스 파일이나 클래스 파일을 생성한다면, 컴파일은 해당 파일이 생성되지 않을 때까지 다시 시작된다.

개념적으로 어노테이션 프로세스는 컴파일 전에 수행되는 예비 단계다.
이 예비 단계는 일련의 라운드로 구성되어 각 라운드는 소스 파일을 구문 분석하고 입력한 후 적절한 어노테이션 프로세서를 결정하고 호출한다. 초기 라운드 이후에는 어노테이션 프로세서 중 어떤 것이라도 새로운 소스 파일이나 클래스 파일을 생성하여 최종 컴파일에 포함되어야 할 경우 추가 라운드가 수행된다. 최종적으로 필요한 모든 라운드가 완료되면 실제 컴파일이 수행된다.

보통 annotation proccessor 를 사용하면 새로운 클래스를 만드는데, lombok 은 process 메서드에서 제공하는 파라미터만 사용하는 게 아니고 ast를 수정가능한 타입으로 downcasting 해 사용하여 클래스를 수정한다.

예제

참고

https://openjdk.org/groups/compiler/doc/compilation-overview/index.html
https://medium.com/yanoljacloud-tech/java-%EC%BD%94%EB%93%9C%EB%8A%94-%EC%96%B4%EB%96%BB%EA%B2%8C-%EC%9E%90%EB%8F%99%EC%9C%BC%EB%A1%9C-%EB%A7%8C%EB%93%A4%EC%96%B4%EC%A7%88%EA%B9%8C-2-2-438f14e94aa8

0개의 댓글