简体   繁体   English

Java批注处理,在与批注的类相同的包中创建源文件

[英]Java Annotation Processing, create a source file in the same package as the annotated class

I am writing an annotation processor for Java in Eclipse. 我在Eclipse中编写Java注释处理器。 I have created an annotation @MyAnnotation intended that any class, say A , annoteted with @MyAnnotation will have an auto-generated "buddy class", A_buddy , which resides in the same package as A . 我创建了一个注释@MyAnnotation ,该注释旨在使任何以@MyAnnotation注释的类(例如A都具有一个自动生成的“伙伴类” A_buddy ,该类与A驻留在同一包中。

So, I am creating the annotation processor to do the work. 因此,我正在创建注释处理器来完成这项工作。 Following is the code. 以下是代码。

@SupportedAnnotationTypes("MyAnnotation")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class MyAnnotationProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) {

        //find and process the annotated class
        ...
        String annotatedClassName = ...; //the name of the annotated class.
        PackageElement pkgElement = ...; //the package of the annotated class.

        //create the source file
        String buddyClassName = annotatedClassName + "_buddy";
        JavaFileObject jfo = processingEnv.getFiler().createSourceFile(buddyClassName, pkgElement);
        Writer writer = jfo.openWriter();

        writer.write("Hello, buddy");
        writer.close();

Saved and Built the code in Eclipse and the buddy file was placed in the .apt-generated folder, which is not what I wish. 在Eclipse中保存并构建代码,并将伙伴文件放置在.apt-generated文件夹中,这不是我想要的。

How to place the generated source file in the same package as the annotated class so that I can refer to it as if I have created it by hand? 如何将生成的源文件与带注释的类放在同一包中,以便可以像手动创建它一样引用它? For example if the annotated class is mypackage.A , I wish that when I save the code in Eclipse, I would get the auto-generated class mypackage.A_buddy such that I can refer to it in other part of code immediately. 例如,如果带注释的类是mypackage.A ,我希望将代码保存在Eclipse中时,我会得到自动生成的类mypackage.A_buddy这样我就可以立即在代码的其他部分引用它。

Open the project properties dialog and go to Java Compiler -> Annotation Processor . 打开项目属性对话框,然后转到Java Compiler -> Annotation Processor If you check the Enable project specific settings you can edit the generated source directory to tell it where to put your generated classes. 如果选中“ Enable project specific settingsEnable project specific settings ,则可以编辑生成的源目录以告诉它将生成的类放在何处。

Alternatively, if you just want to reference the classes in your other code, you can add the .apt_generated folder as a source folder in the project properties Java Build Path section. 另外,如果您只想引用其他代码中的类,则可以在项目属性“ Java Build Path部分中将.apt_generated文件夹添加为源文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM