I'm writing a Java annotation processor that creates package-info for packages in a Java project.
The code to actually generate the source file looks somewhat like this:
JavaFileObject builderFile = filer.createSourceFile(packageName + ".package-info");
try (PrintWriter out = new PrintWriter(builderFile.openWriter()))
{
out.println("... file content ...");
}
Unfortunately, this code crashes when there already is a package-info for the given package, either in the source code or generated by a previous round.
Normally, I would just skip the generation if a package-info already exists, but I couldn't find any way to test for the existence of a package-info.
processingEnv.getElementUtils().getPackageElement(packageName)
Always returns a PackageElement, regardless of whether there is a package-info or not, which seams reasonable, because the package exists with or without the package-info.
There also doesn't seem to be an ElementKind for package-info either and PackageElement.getEnclosedElements() only returns the top level classes and interfaces in that package.
In lack of a better solution, I'm currently catching and ignoring the IOException thrown by Filer.createSourceFile(String) in case the package-info already exists.
Is there a way to check if a certain package already contains a package-info?
Edit:
FWIW, the source file can be found on Github