[英]Java Annotation Processing, create a source file in the same package as the annotated class
我在Eclipse中編寫Java注釋處理器。 我創建了一個注釋@MyAnnotation
,該注釋旨在使任何以@MyAnnotation
注釋的類(例如A
都具有一個自動生成的“伙伴類” A_buddy
,該類與A
駐留在同一包中。
因此,我正在創建注釋處理器來完成這項工作。 以下是代碼。
@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();
在Eclipse中保存並構建代碼,並將伙伴文件放置在.apt-generated
文件夾中,這不是我想要的。
如何將生成的源文件與帶注釋的類放在同一包中,以便可以像手動創建它一樣引用它? 例如,如果帶注釋的類是mypackage.A
,我希望將代碼保存在Eclipse中時,我會得到自動生成的類mypackage.A_buddy
這樣我就可以立即在代碼的其他部分引用它。
打開項目屬性對話框,然后轉到Java Compiler -> Annotation Processor
。 如果選中“ Enable project specific settings
於Enable project specific settings
,則可以編輯生成的源目錄以告訴它將生成的類放在何處。
另外,如果您只想引用其他代碼中的類,則可以在項目屬性“ Java Build Path
部分中將.apt_generated
文件夾添加為源文件夾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.