如何使用在Java构建的时间标注动态地生成code? [英] How to generate code dynamically with annotations at build time in Java?

查看:103
本文介绍了如何使用在Java构建的时间标注动态地生成code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找产生code的解决方案。我用Google搜索,所以搜索了一些博客,但我没有找到一个好的解决办法。

我想放在注释上我的课,并在编译时,一些方法和属性会自动添加到类中。

我正在寻找解决方案的关键点:


  • 生成code定制(必选)

  • 无外部工具,如已被称为(必选)

  • JDK而已,没有任何第三方的框架(强制性)

  • 注释名称自定义(可选)

例如:

  @Alias​​able
公共类MyClass的{
//一些性质//构造器...//一些方法
}

我的阶级是这样的编译后:

 公共类MyClass的{
   //一些性质
   私人字符串别名;   //构造器...   //一些方法
   公共字符串getAlias​​(){
      返回别名;
   }   公共无效setAlias​​(字符串别名){
      this.alias =别名;
   }
}


解决方案

借助 已集成的注释处理工具的javac 的,因为1.6版本,并且 JDK的的一部分。因此,有没有需要外部工具使用的可插拔注解API时的。您可以生成通过分析使用的镜像API

您不能/不应该改变现有的类虽然。可以通过创建子类来生成扩展方法。

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 :

  • Generated code customizable (MANDATORY)
  • No external tool like apt have to be called (MANDATORY)
  • JDK only, no third-party framework (MANDATORY)
  • Annotation name customizable (OPTIONAL)

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

解决方案

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.

You can't/shouldn't change existing classes though. Extension methods can be generated by creating subclasses.

这篇关于如何使用在Java构建的时间标注动态地生成code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆