I am building an annotation processor plugin for eclipse, what i would like to do is to examine several files inside the project folder during the processing.
I wou
The processing environment provides you with a Filer that can be used to load (known) resources. If you need absolute paths to discover files or directories, you can use a JavaFileManager and a StandardLocation:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
Iterable<? extends File> locations = fm.getLocation(StandardLocation.SOURCE_PATH);
If you are using Eclipse, you need to configure it to use the JDK as runtime as bennyl pointed out in the comments.
It seems that there is no API that is obligated to return the source location, so the solution above won't work reliably and only with some environments. The Filer for example is only required to support CLASS_OUTPUT
and SOURCE_OUTPUT
.
The easiest workaround is probably to assume/require a specific project structure, where the source directories and compiled classes are in a specific subdirectories of the project (e.g. the src
and bin
directories for most IDEs or src/main/java
and target/classes
for Maven). If you do that, you can get the source path by creating a temporary resource with the Filer
at the SOURCE_OUTPUT
location and get the source path relative from that file's location.
Filer filer = processingEnv.getFiler();
FileObject resource = filer.createResource(StandardLocation.CLASS_OUTPUT, "", "tmp", (Element[]) null);
Path projectPath = Paths.get(resource.toUri()).getParent().getParent();
resource.delete();
Path sourcePath = projectPath.resolve("src")
I am getting the source path from ProsessingEnv
by generating a source file:
String fetchSourcePath() {
try {
JavaFileObject generationForPath = processingEnv.getFiler().createSourceFile("PathFor" + getClass().getSimpleName());
Writer writer = generationForPath.openWriter();
String sourcePath = generationForPath.toUri().getPath();
writer.close();
generationForPath.delete();
return sourcePath;
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Unable to determine source file path!");
}
return "";
}