javaannotationsgenerated-code

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


I'm looking for a solution for generating code. I have googled, searched on SO and some blogs but I didn't find a good solution.

I'd like to put an annotation on my class and at compilation time, some methods and properties would be automatically added to the class.

Key points of the solution I'm looking for :

For example :

@Aliasable
public class MyClass {
//Some properties

// Contructor ...

// Some methods
}

My class would look like this after compilation :

public class MyClass {
   //Some properties
   private String alias;

   // Contructor ...

   // Some methods
   public String getAlias() {
      return alias;
   }

   public void setAlias(String alias) {
      this.alias=alias;
   }
}

EDIT:
Finally, I turned my third requirement from MANDATORY to OPTIONAL and choosed project Lombok (easy integration with Maven and Eclipse, virtually no work to do for using it).


Solution

  • 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.