我正在努力理解JavaCompiler.getTask()
。我理解所有参数,除了第二个到最后一个名为classes
的参数。 Javadoc读到:
类名(用于注释处理),null表示没有类名
但我不明白他们的意思。我发现很多网站都在线引用JavaCompiler,但没有一个网站解释这个参数。有什么想法吗?
答案 0 :(得分:2)
我相信当你想在二进制文件上运行注释处理器时可以使用它。这些类将是您要处理的类型。
演示代码:
public class MyProcessor extends AbstractProcessor {
public static @interface X { String value(); }
@X("Hello") public static class Y {}
@Override public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (Element element : roundEnv.getRootElements()) {
X x = element.getAnnotation(X.class);
if (x != null) System.out.println(x.value());
}
return true;
}
@Override public Set<String> getSupportedAnnotationTypes() {
return new HashSet<String>(Arrays.asList(X.class.getCanonicalName()));
}
@Override public SourceVersion getSupportedSourceVersion() {
return SourceVersion.RELEASE_6;
}
public static void main(String[] args) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
List<String> classes = Arrays.asList(Y.class.getCanonicalName());
List<String> options = Arrays.asList("-processor", MyProcessor.class
.getCanonicalName());
CompilationTask task = compiler.getTask(null, null, null, options, classes,
null);
task.call();
}
}
以上代码打印出"Hello"
。