Eclipse - Annotation processor, get project path

后端 未结 2 1654
南方客
南方客 2020-12-21 11:05

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

2条回答
  •  Happy的楠姐
    2020-12-21 11:17

    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 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")
    

提交回复
热议问题