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



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

我想知道如何从我的处理器内获得项目路径。我相信这是可以做到的,因为项目源路径提供给处理器-但我找不到到达它的方法。

我试着看看系统。属性和processingEnv.getOptions(),但没有有用的信息…

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

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

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
Iterable<? extends File> locations = fm.getLocation(StandardLocation.SOURCE_PATH);

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


似乎没有API必须返回源位置,所以上面的解决方案不能可靠地工作,只适用于某些环境。例如,filter只支持CLASS_OUTPUTSOURCE_OUTPUT

最简单的解决方法可能是假设/需要一个特定的项目结构,其中源目录和编译类位于项目的特定子目录中(例如,大多数ide的srcbin目录或Maven的src/main/javatarget/classes目录)。如果您这样做,您可以通过在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 "";
}

最新更新