[英]Annotation Processor Links to a file
您可以找到包含注釋元素的頂級 class,從中派生文件名和 package 名稱,並將它們傳遞給Filter.getResource 。 返回的 FileObject 可以使用其toUri()
方法轉換為 URI。
if (baseUrl.isEmpty()) {
String filename = null;
String packageName = null;
Element owner = element;
do {
if (owner instanceof TypeElement type
&& type.getNestingKind() == NestingKind.TOP_LEVEL) {
filename = type.getSimpleName() + ".java";
PackageElement pkg =
processingEnv.getElementUtils().getPackageOf(type);
packageName = pkg.getQualifiedName().toString();
ModuleElement mod =
processingEnv.getElementUtils().getModuleOf(type);
if (mod != null && !mod.isUnnamed()) {
packageName = mod.getQualifiedName() + "/" + packageName;
}
break;
}
owner = owner.getEnclosingElement();
} while (owner != null);
String fileLocation = "(file unknown)";
if (filename != null && packageName != null) {
try {
FileObject file = processingEnv.getFiler().getResource(
StandardLocation.CLASS_PATH, packageName, filename);
fileLocation = file.toUri().toString();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Note: The url field must not be empty, " + fileLocation, element);
}
上面的代碼假設element
是RoundEnvironment.getElementsAnnotatedWith (或 RoundEnvironment.getElementsAnnotatedWithAny)返回的 Element。
您的圖像顯示的是絕對文件路徑,而不是 URL。 如果您真的想要一個文件路徑,而不是 URL,那么獲取一個而不是 URI 很容易:
Path path = Paths.get(file.getName());
fileLocation = path.toAbsolutePath().toString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.