Source View Technology: Combining the Strengths of APT and AST
Background Take Lombok as an example: at compile time, it reads annotations like @Getter and @Setter through an Annotation Processor (APT, Annotation Processing Tool), then directly modifies the AST (Abstract Syntax Tree) in memory, injecting getter/setter methods for fields. Developers only need to annotate fields, and the compiled .class files automatically include these methods. Advantages of APT APT is an extension mechanism natively supported by the Java compiler. Annotation processors run at compile time and can read annotation information from source code to generate new source files. Its advantages are: Standardized — Simply implement the Processor interface; no need to hack the compiler Composable — Multiple annotation processors can work together in the same compilation process Generated code is visible — Source files generated through the Filer API are located in the build/generated/ directory, and IDEs can navigate to them after configuring the source path Disadvantages of APT APT has a fundamental limitation: it cannot generate a class with the same fully qualified name as the source code. The Java compiler explicitly specifies that two classes with the same fully qualified name are not allowed in the same compilation unit. Source code generated by APT participates in the same round of compilation as the original source code, so it can never generate a class with the same fully qualified name as the original class. This means APT cannot truly "modify" a class; it can only generate new classes (such as Builder, Factory, etc.). Advantages of AST Tools like Lombok bypass the APT limitation by directly modifying the AST in the compiler's memory — injecting methods for fields, injecting constructors for classes, etc. The advantages of AST modification are: Can modify existing classes — Methods are added directly to the AST in memory, breaking through the limitation that APT cannot generate Same-Name Classes Zero intrusion — Classes written by developers rema