如何在 Java 构建时动态生成带有注释的代码?

问题描述:

我正在寻找生成代码的解决方案.我用谷歌搜索过,搜索过 SO 和一些博客,但没有找到好的解决方案.

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 :

  • 生成的代码可定制(强制性)
  • 无需调用像 apt 这样的外部工具(强制性)
  • 仅 JDK,无第三方框架(强制性 可选)
  • 注释名称可自定义(可选)
  • Generated code customizable (MANDATORY)
  • No external tool like apt have to be called (MANDATORY)
  • JDK only, no third-party framework (MANDATORY OPTIONAL)
  • Annotation name customizable (OPTIONAL)

例如:

@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;
   }
}


最后,我将我的第三个要求从 MANDATORY 变成了 OPTIONAL 并选择了 project Lombok(与 Maven 和 Eclipse 轻松集成,几乎没有工作去做使用它).


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

查看 Project Lombok.它会按照您编写时的要求生成代码:

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.