繁体   English   中英

注释处理器链接到文件

[英]Annotation Processor Links to a file

我确实制作了我的自定义注释处理器 class,它工作正常,但我想在引发错误时打印一条消息,并添加引发该错误的文件链接。

        if(baseUrl.isEmpty()) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Note: The url field must not be empty, {@link Endpoints.java:9}");
        }

我怎样才能像这样打印 url 在此处输入图像描述

您可以找到包含注释元素的顶级 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);
}

上面的代码假设elementRoundEnvironment.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.

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