Eclipse – Annotation处理器,获取项目路径

我正在为eclipse构建一个注释处理器插件,我想要做的是在处理过程中检查项目文件夹中的几个文件。

我想知道如何从我的处理器中获取项目路径。 我相信这可以做到,因为项目源路径提供给处理器 – 但我找不到一种方法来达到它。

我试着查看System.properties和processingEnv.getOptions(),但那里没有有用的信息..

最后我想在Netbeans上使用这个注释处理器,所以如果有一个公共API可以提供这些信息,那将是最好的 – 但任何帮助将不胜感激..

处理环境为您提供了可用于加载(已知)资源的Filer 。 如果需要绝对路径来发现文件或目录,可以使用JavaFileManager和StandardLocation

 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null); Iterable locations = fm.getLocation(StandardLocation.SOURCE_PATH); 

如果您正在使用Eclipse,则需要将其配置为使用JDK作为运行时,如注释中指出的bennyl。


似乎没有API有义务返回源位置,因此上述解决方案将无法可靠地工作,并且仅适用于某些环境。 例如,Filer仅需要支持CLASS_OUTPUTSOURCE_OUTPUT

最简单的解决方法可能是假设/需要特定的项目结构,其中源目录和编译的类位于项目的特定子目录中(例如,大多数IDE的srcbin目录或src/main/javatarget/classes的Maven的)。 如果这样做,您可以通过在SOURCE_OUTPUT位置创建Filer的临时资源来获取源路径,并从该文件的位置获取相对的源路径。

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

我通过生成源文件从ProsessingEnv获取源路径:

 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 ""; }