Eclipse - Annotation processor, get project path

痴心易碎 提交于 2019-11-29 16:14:07

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 "";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!