如何在Java注释处理器中获取正确的JavaFileManager?

时间:2015-04-15 18:41:19

标签: java eclipse annotation-processing

我通过扩展在Eclipse上下文中调用的javax.annotation.processing.AbstractProcessor来编写Java注释处理器并且它工作正常,除了我需要有关处理器的源路径和类路径的更多信息:< / p>

@SupportedAnnotationTypes({"MyAnno"})
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class Processor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        // this used to work in Java4 but not anymore (since Java6?):
        String sourcePath = processingEnv.getOptions().get("sourcepath");
        String classPath = processingEnv.getOptions().get("classpath");

        for (Element e : roundEnv.getElementsAnnotatedWith(MyAnno.class)) {
            myProcess(e, sourcePath, classPath); 
        }

        return true;
    }
}

问题是如何在注释处理上下文(process的实现)中检索一个有效的JavaFileManager,它可以为我提供源路径和当前正在执行注释的编译器的类路径处理器。最好是,我会找到一个不涉及对Eclipse / JDT特定接口的依赖的解决方案。

我尝试过工作的以下内容:

DiagnosticCollector<JavaFileObject> diagnostics =
                   new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(diagnostics, null, null);
fm.getLocation(StandardLocation.CLASS_PATH); // prints an empty class path

1 个答案:

答案 0 :(得分:0)

对于 Java 8 及更早版本:

import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.util.Context;
import javax.annotation.processing.ProcessingEnvironment;

    protected static JavaFileManager getJavaFileManager(ProcessingEnvironment env) {
        JavaFileManager fm = null;

        if (env instanceof JavacProcessingEnvironment) {
            Context context = ((JavacProcessingEnvironment) env).getContext();

            fm = context.get(JavaFileManager.class);
        }

        return fm;
    }

对于 Java 9 和 10 及更高版本(和 8),使用反射来避免挠痒痒 bug

    protected static JavaFileManager getJavaFileManager(ProcessingEnvironment env) {
        JavaFileManager fm = null;

        try {
            /*
             * Context context = ((JavacProcessingEnvironment) env).getContext();
             */
            Method getContext = env.getClass().getMethod("getContext");
            Object context = getContext.invoke(env);
            /*
             * fm = context.get(JavaFileManager.class);
             */
            Method get = context.getClass().getMethod("get", Class.class);

            fm = (JavaFileManager) get.invoke(context, JavaFileManager.class);
        } catch (Exception exception) {
        }

        return fm;
    }