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

CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
roberto
  • 163
  • 1
  • 11
  • 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](https://www.baeldung.com/java-annotation-processing-builder) out. It describes how to implement that exactly. For code generation, there are several libraries you can use. – CodeMatrix Nov 06 '20 at 08: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 – roberto Nov 06 '20 at 10:14
  • 2
    Exactly, for that, there are some libraries existent that allow you to modify existing classes. E. g. [byte-buddy](https://github.com/raphw/byte-buddy) or [ASM](https://asm.ow2.io/). You can also read something about that in [this](https://stackoverflow.com/questions/13690272/code-replacement-with-an-annotation-processor) post. There are 2 answers that may help you more out. – CodeMatrix Nov 06 '20 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 – roberto Nov 06 '20 at 14:01

0 Answers0