Eclipse - 注释处理器,获取项目路径

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

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 would like to know how can I get the project path from within my processor. I believe this can be done because the project source path is provided to the processor - but I cannot find a way to reach it.

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

I tried looking at the System.properties and at the processingEnv.getOptions() but there is no useful information there..

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

eventually I would like to use this annotation processor on Netbeans too so if there is a public API that can provide this information it will be the best - but any help will be appreciated..

推荐答案

处理环境为你提供了一个Filer 可用于加载(已知)资源.如果您需要绝对路径来发现文件或目录,可以使用 JavaFileManager 和 标准位置:

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

如果您使用的是 Eclipse,您需要将其配置为使用 JDK 作为运行时,正如 bennyl 在评论.

If you are using Eclipse, you need to configure it to use the JDK as runtime as bennyl pointed out in the comments.

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

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.

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

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

相关文章