How to generate code dynamically with annotations at build time in Java?

ぃ、小莉子 提交于 2019-11-28 18:19:19

Have a look at Project Lombok. It generates code as you ask when you write:

public class MyClass {
  @Getter @Setter private String alias;
}

It also does a lot more if you need it. I know you asked for no external tools, but you would basically be recreating this.

The annotation processing tool has been integrated in javac since version 1.6 and is part of the JDK. So there is no need for external tools when using the Pluggable Annotation API. You can generate any code by analysing custom annotations or method/parameter/field/class declarations using the Mirror API.

The annotation processor API says you shouldn't change existing classes. Instead you should generate subclasses of existing classes and create extension methods on those subclasses.

It seems to be possible to change classes anyway (e.g. by using bytecode manipulation libraries) though that would in contrast to the specification and could lead to issues with other annotation processors and may not work with all compilers in the same way.

I use XML and XSLT to generate code. It is used for EJB, Logic and the CRUD part of the views. It isnt gerated at runtime but instead on the buildserver. Developers can generate the code manually for well development purposes. This is done with the same command ANT uses on the buildserver.

Because the generation is with XML and XSLT it is highly customizable.

If you google Java code generation with XSLT you will run into alot of examples. Please note that this technique dates from ~2000 and thus probably has been preceded by now by easier solutions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!