[英]How to get the class code as String from Annotation Processor?
我有一個基本的注釋處理器
@SupportedAnnotationTypes("example.Annotation")
public class Processor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(annotation);
for (Element element : elementsAnnotatedWith) {
TypeElement typeElement = (TypeElement) element;
// Here, typeElement.getQualifiedName() is accessible, but not the code nor file path.
}
}
return false;
}
}
此注解只能用於類。 我知道目標 class 未編譯,因此無法進行反射訪問,但我想將 class 代碼作為字符串以我自己的方式解析,而不是使用此 API。
可能嗎? 我知道我可以獲得限定名稱,但在哪里查找文件?
TypeElement
的源代碼可以這樣加載:
private String loadSource(TypeElement typeElement) throws IOException {
final FileObject source = processingEnv.getFiler().getResource(
StandardLocation.SOURCE_PATH,
((PackageElement) typeElement.getEnclosingElement()).getQualifiedName(),
typeElement.getSimpleName() + ".java");
try (Reader reader = source.openReader(true)) {
final StringBuilder builder = new StringBuilder();
final char[] buf = new char[1024];
int read;
while ((read = reader.read(buf)) != -1) {
builder.append(buf, 0, read);
}
return builder.toString();
}
}
測試的Processor
jar 包含一個META-INF/services/javax.annotation.processing.Processor
文件,無需指定-process
選項:
src/main/java
是源目錄tasks.withType(JavaCompile) {
configure(options) {
options.setSourcepath(project.files('src/main/java'))
}
}
-sourcepath
選項: javac -cp path/to/processor.jar -sourcepath path/to/sources path/to/JavaFile.java
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.