5

I want to create a java annotation which generates a method in compile-time, like Lombok for example: I have this class :

@MyNewAnnotation() public class ClassTest { private String name; private Integer id; private String lastName; public final static String COL_NAME = "NAME"; public final static String COL_LAST_NAME = "LAST_NAME"; } 

I want that's myNewAnnotation can generate the getCol-method which returns "NAME, LAST_NAME" for example:

public static String getCol() { return COL_NAME + "," + COL_LAST_NAME; } 

The annotation has to read all attributes which start with "COL_" and with them generate the new method in compile-time, more or less like Lombok when generating getters or setters

4
  • 2
    You would need to write your own compile-time annotation processor. That is the only way you can generate methods for the runtime. Lombok uses its own annotation processors to be able to use these methods in development and for the generation of runtime code. E. g. @Getter doesn't generate the method until you compile/build your project. Please check this out. It describes how to implement that exactly. For code generation, there are several libraries you can use. Commented Nov 6, 2020 at 8:58
  • I have seen the article, but the article said ** An important thing to note is the limitation of the annotation processing API — it can only be used to generate new files, not to change existing ones.**, and i don't want to creat another class, i want generate my method in the same class Commented Nov 6, 2020 at 10:14
  • 2
    Exactly, for that, there are some libraries existent that allow you to modify existing classes. E. g. byte-buddy or ASM. You can also read something about that in this post. There are 2 answers that may help you more out. Commented Nov 6, 2020 at 10:25
  • Okey then using only annotation is impossible to modify a class and add it new mrthod? if i don't use these libreries Commented Nov 6, 2020 at 14:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.