Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file from src/main/resources with annotation processor?

I have a simple annotation processor that needs to read a configuration file from the same project as the annotated classes. Example structure:

- myproject 
  - src
    - main
      - java
        - my.package.SourceFile
      - resources
        - config.json

In the annotation processor, I try to read the file:

FileObject resource = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, "", "config.json");

but it throws FileNotFoundException. I also tried other paths, such as ../resources/config.json, (which throws Invalid relative name: ../resources/config.json). And I tried putting the config file in src/main/java (and even src/main/java/my/package) instead, which I don't like, but that also still throws FileNotFoundException.

It would already help if I could get filer.getResource() to tell me where it's looking. To find that out, I tried generating a file:

filer.createResource(StandardLocation.SOURCE_OUTPUT, "", "dummy");

which generated in myproject/build/classes/main/dummy. Unfortunately, I can't generate in SOURCE_PATH, so that doesn't help with finding this out.

like image 659
Jorn Avatar asked Sep 29 '16 13:09

Jorn


2 Answers

I'd expect that the stuff from src/main/resources gets copied to target/classes during the build (prior to annotation processing). In that case you can open them like this:

ProcessingEnvironment pe = ...;
FileObject fileObject = pe.getFiler()
    .getResource( StandardLocation.CLASS_OUTPUT, "", "config.json" );
InputStream jsonStream = fileObject.openInputStream();
like image 77
Gunnar Avatar answered Nov 15 '22 18:11

Gunnar


I've looked at this with one of the Project Lombok developers. If anyone knows annotation processing, it's them ;)

Our conclusion was, that the JavacFileManager that handles the request internally, does not have a path to resolve StandardLocation.SOURCE_PATH to. We're not sure, but it might be related to building with Gradle.

like image 34
Jorn Avatar answered Nov 15 '22 19:11

Jorn