简体   繁体   中英

Generate Methods in annotation processors

I have an annotation processor that checks the classes annotated with @Builder if they have setters for every field (and generates builder class based on those methods). Now it is possible to generate those setters methods (if they dont exist) before my annotation processor kicks in?

I know that a annotation processor can only generate new files and not manipulate any existing ones.Also libraries like ASM and Javassist work with.class files that do not exist when the annotation processor is used. Any suggestions?

Project Lombok - and note how lombok includes plugins and special tooling for many many dev tools (such as IntelliJ, VSCode, Eclipse, GWT, gradle, maven, many many versions of javac, NetBeans, etc) and is a lot of lines of code.

The Annotation Processor API simply does not include options to add/change things in existing files. Hence why you need to write this logic for every platform you care to target, which is slightly easier than it sounds as there is a limited set of actual baseline java parsers/compilers out there (basically, ecj and javac - on top of which most things are built), so eg lombok's VSCode integration is very simple (as VSCode uses an eclipse-based language server, so 95% of the work for VSCode and Eclipse is shared), but I chose the word slightly rather intentionally there.

In other words, not possible unless you want to spend a few personyears. Or fork Lombok.

DISCLAIMER: I'm a core contributor to Project Lombok.

Short answer is no, if you want to keep it clean and stay away from something like lombok, Annotation processors are all about generating new classes not changing existing classes, as for your case you actually should not do something like, but your annotation processor should check if the setter exists then you use the setter if not you just assign the field directly expecting the field to have a proper visibility scope, if it is not then you get a compiler error letting the user to know that he needs to expose those fields.

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