简体   繁体   中英

Java: How to write an annotation that adds a default constructor to a class

The question is already in the title and it's the less specific version of a question I asked earlier :

How do you write an annotation in java that adds a default constructor to a class?

There is a project which already does that: http://projectlombok.org/

Technically, you need to hook into the Java compiler. Compiling Java code is done in phases: First, all the sources are collected. Then the parser creates an AST. The code generation phase then turns the AST into byte code.

Annotation processors are run after the AST has been built but before the byte code is generated. By modifying the AST, you can modify the resulting class file.

This blog post contains the details: http://notatube.blogspot.com/2010/11/project-lombok-trick-explained.html

As I understand Lombok, it contains all the tools to write additional AST transformers which get triggered by custom annotations.

This is generally not supported, AFAIK.

Project Lombok does something like this, but it uses some hacks AFAIK.

https://blogs.oracle.com/darcy/entry/properties_via_annotation_processing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM