如何使用 Java 1.6 Annotation Processing 执行编译时编织? [英] How do you use Java 1.6 Annotation Processing to perform compile time weaving?

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

问题描述

我创建了一个注释,将它应用到 DTO 并编写了一个 Java 1.6 样式的 annotationProcessor.我可以看到如何让 annotationProcessor 编写一个新的源文件,这不是我想要做的,我看不到或不知道如何让它修改现有类(最好只修改字节码).修改实际上相当简单,我希望处理器做的就是插入一个新的 getter 和 setter,其中名称来自正在处理的注释的值.

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 Annotation Processing 执行编译时编织?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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