1

Im writing an annotation processor for android projects. I want to get the absolute path of the androids resource folder (I know it's configureable through gradle, but I ignore this case for now).

My idea is to get the absolute path of an processed element:

@MyAnnotation public class Foo{ ... }

So in my AnnotationProcessor I want to get the path to Foo.java.

  @Override public boolean process(Set<? extends TypeElement> annotations,
      RoundEnvironment roundEnv) {

    for (Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class))

      try {
        ProcessorMessage.info(element, "Path: %s %s", getWorkingDir(), getExecutionPath());
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        ProcessorMessage.error(element, "Error " + e.getMessage());
      }

    return false;
  }

  private String getExecutionPath() throws UnsupportedEncodingException {
    String path = AnnotatedAdapterProcessor.class.getProtectionDomain()
        .getCodeSource()
        .getLocation()
        .getPath();
    String decodedPath = URLDecoder.decode(path, "UTF-8");

    return decodedPath;
  }

  private String getWorkingDir() {
    Path currentRelativePath = Paths.get("");
    String s = currentRelativePath.toAbsolutePath().toString();
    return s;
  }

However it gives me the following output:

Path: /Users/XXXXX/.gradle/daemon/1.12 /Users/XXXXX/.m2/repository/com/example/myprocessor/processor/0.1.2-SNAPSHOT/processor-0.1.2-SNAPSHOT.jar

Is there a way to get the path where Foo.java is located? (Just to get a startpoint from where I will continue to start searching for the resource folder)

sockeqwe
  • 15,574
  • 24
  • 88
  • 144

1 Answers1

1

I think those paths probably depend on your build environment and if you construct them by hand it's possible that they won't work on every machine or with every IDE.
This question might help: Annotation processor, get project path

If that doesn't work I think you are still on the right track there, but should try using the actual resources instead of classes loaded by for the processor, like this:

String path = Foo.class.getProtectionDomain().getCodeSource().getLocation().getPath();

I'm not sure if this all also applies in the context of processors, but in general this should give you the root output directory of the class file:

String path = Foo.class.getClassLoader().getResource(".").getFile();

If you know that the output directory for example is in your_project/target/classes, you could use that get to the source or resource directory.

Community
  • 1
  • 1
kapex
  • 28,903
  • 6
  • 107
  • 121
  • 1
    the .getClassLoader().getResource(".").getFile() version did the trick for me in Netbeans with compile on save active. No other way worked – Thomas Oster Aug 08 '19 at 04:48