1

I did make my custom annotation processor class, and it's working fine, but I would like to print a message when raise an error, and add the link of file where raise that error.

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

How can I print the url like this enter image description here

2
  • Does it have to be a link? You can just pass the annotated Element as a third argument to printMessage, which will cause the compiler to print the location. Commented Dec 30, 2021 at 17:24
  • I would like to allow to users to click on location and open the file which actually have the error, pointing the line.. Commented Dec 30, 2021 at 19:14

1 Answer 1

2

You can find the top-level class which encloses the annotated element, derive the file name and package name from it, and pass them to Filer.getResource. The returned FileObject can be converted to a URI with its toUri() method.

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); } 

The above code assumes element is an Element returned by RoundEnvironment.getElementsAnnotatedWith (or RoundEnvironment.getElementsAnnotatedWithAny).

Your image shows an absolute file path, not a URL. If you really wanted a file path, not a URL, it’s easy enough to obtain one instead of a URI:

Path path = Paths.get(file.getName()); fileLocation = path.toAbsolutePath().toString(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, I will try and let you know if it works!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.