【问题标题】:How can I get the working directory of a project from an Annotation Processor in Java如何从 Java 中的注释处理器获取项目的工作目录
【发布时间】:2014-10-01 06:39:11
【问题描述】:

我正在用 Java 编写一个注释处理器,在这个注释处理器中,我希望能够在我正在使用这个注释处理器的项目的项目层次结构中找到一个文件。通过注释,我可以传入我正在搜索的文件相对于项目根目录的路径,但我无法检索项目的工作目录。

假设处理器是 MyCustomProcessor,我在项目 MyProject 中使用它。我希望能够通过 MyCustomProcessor 的“进程”方法从 MyProject 的项目结构中访问(读取)文件(属性文件)。

我已经阅读了这个链接Eclipse - Annotation processor, get project path,但是当我使用他们的解决方案时,我从StandardJavaFileManager.getLocation(StandardLocation.SOURCE_PATH) 调用中返回了一个空值。

关于实现的更多细节:

MyAnnotationProcessor:

@SupportedAnnotationTypes(value = {"MyAnnotation" })
@SupportedSourceVersion(RELEASE_6)
public class MyCustomProcessor extends AbstractProcessor {
...

@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
    for (final Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
<!-- Here is where I would like to get the working directory !-->
}
 }
}

有关测试和开发环境的更多详细信息:Eclipse Kepler、JRE 1.7。

如果您需要更多详细信息,请询问。

【问题讨论】:

  • 这是一个老问题,但仅供参考:我使用 this.getClass().getClassLoader().getResource(".").getFile() 来获取放置类文件的目录和至少在 netbeans 上,这是在项目根目录下,并且资源文件也被复制到该位置(即使在更改时)

标签: java working-directory annotation-processing


【解决方案1】:

对该答案的评论指出这个问题是一个解决方案:null JavaCompiler in Eclipse

有些工具未在 JRE 中实现,仅在 JDK 中可用。 Eclipse 似乎默认使用 JRE 运行处理器,因此您需要将项目配置为使用 JDK 作为运行时。

【讨论】:

  • 感谢您的回答。事实上,与此同时,我从 JRE 1.7 切换到 jdk 1.7,并将 lib 文件夹中的 tools.jar 添加到 jdk。不幸的是,我没有得到一个 null JavaCompiler,只是一个 null StandardJavaFileManager.getLocation(StandardLocation.SOURCE_PATH),这意味着我无法获取源路径。
  • 使用 maven-processor-plugin:2.2.4 对我也不起作用。 fm.getLocation(StandardLocation.SOURCE_PATH) 返回 null。只有返回不为 null 的 StandardLocations 是无用的:CLASS_PATH 包含位置 /opt/buildmanagement/hudson/slaves/slave_1/maven3-agent.jar 和 /opt/buildmanagement/hudson/tools/apache-maven-3.0.5/boot/plexus-classworlds -2.4‌​.jar; PLATFORM_CLASS_PATH 包含一些 JAR。其余为空。
猜你喜欢
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-29
  • 1970-01-01
相关资源
最近更新 更多