你如何使用Java 1.6注解处理进行编译时织入? [英] How do you use Java 1.6 Annotation Processing to perform compile time weaving?

查看:200
本文介绍了你如何使用Java 1.6注解处理进行编译时织入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个注解,它适用于DTO和书面一个Java 1.6风格annotationProcessor。我可以看到有annotationProcessor写一个新的源文件,这是不是我想做的事情,我无法看到或了解如何把它修改现有的类(理想情况下只需修改一个字节code)。修改实际上是相当琐碎,我要的处理器做是插入一个新的getter和setter所在的名字来源于被处理的注解的值。

我的注释处理器看起来是这样的;

  @SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({com.kn.salog.annotation.AggregateField})
公共类SalogDTOAnnotationProcessor继承AbstractProcessor ​​{    @覆盖
    公共布尔过程(最后一组与LT ;?延伸TypeElement>的注释,最终RoundEnvironment roundEnv){
        //做一些东西
    }
}


解决方案

在设计上,注释处理工具不允许源$ C ​​$ C的直接修改正在处理中。但是,可以产生被处理的类型的子类或正被处理的类型的在即可。与一些规划,这并允许部分的修改有关的类型的效果。我已经写了这是如何能够结合在一起的例子。看到此博客条目​​,了解更详细的解释,有些样品code。

I have created an annotation, applied it to a DTO and written a Java 1.6 style annotationProcessor. I can see how to have the annotationProcessor write a new source file, which isn't what I want to do, I cannot see or find out how to have it modify the existing class (ideally just modify the byte code). The modification is actually fairly trivial, all I want the processor to do is to insert a new getter and setter where the name comes from the value of the annotation being processed.

My annotation processor looks like this;

@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({ "com.kn.salog.annotation.AggregateField" })
public class SalogDTOAnnotationProcessor extends AbstractProcessor {

    @Override
    public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
        //do some stuff
    }
}

解决方案

By design, the annotation processing facility does not allow direct modification of the source code being processed. However, one can generate subclasses of the type being processed or the superclass of the type being processed. With some planning, this does allow some of the effect of modifying the type in question. I've written up an example of how this can fit together; see this blog entry for a more detailed explanation and some sample code.

这篇关于你如何使用Java 1.6注解处理进行编译时织入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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