Question

Considering the annotation processing programming model, it is well established how to obtain a reference to the compiler context from within an annotation processor with something like this:

context = ((JavacProcessingEnvironment) this.processingEnv).getContext();

This compiler context can be used when a reference is needed to an internal compiler facility like Attr, Enter, MemberEnter, TreeMaker, etc. via an instance method call:

make = TreeMaker.instance(context);

However, using the Java 8 plugin mechanism, how can one reference com.sun.tools.javac.util.Context instances? The documentation states:

Within the compiler, a single Context is used for each invocation of the compiler. The context is then used to ensure a single copy of each compiler phase exists per compiler invocation.

so within a plugin, whereas a reference to the JavacTask is passed (effectively BasicJavacTask), how can the context object of the current compiler phase be retrieved?

Was it helpful?

Solution

Calling getContext() will not work with the Java 8 compiler plugin mechanism:

((JavacTaskImpl) task).getContext()

For example:

import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.main.JavaCompiler;
// ...

JavacTask javacTask = getJavacTask();
Context context = ((JavacTaskImpl)javacTask).getContext();
JavaCompiler compiler = JavaCompiler.instance( context );

Note, however, that com.sun.tools.javac.main.JavaCompiler does not implement the javax.tools.JavaCompiler interface, and its API is therefore unavailable using this technique. Further, heed the warning for JavacTaskImpl and com.sun.tools.javac.main.JavaCompiler:

This is NOT part of any supported API. If you write code that depends on this, you do so at your own risk. This code and its internal interfaces are subject to change or deletion without notice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top