I am trying to write an annotation processor in Java 6. I wrote a sample implementation, which creates a new source file in the process method and it works fine.
@SupportedAnnotationTypes(value = {"*"})
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class BrownfieldAnnotationProcessor extends AbstractProcessor{
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
try {
JavaFileObject f = processingEnv.getFiler().
createSourceFile("in.test.ExtraClass");
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
"Creating " + f.toUri());
Writer w = f.openWriter();
try {
PrintWriter pw = new PrintWriter(w);
pw.println("package in.test;");
pw.println("public class ExtraClass implements TestInterface{");
pw.println(" public void print() {");
pw.println(" System.out.println(\"Hello boss!\");");
pw.println(" }");
pw.println("}");
pw.flush();
} finally {
w.close();
}
} catch (IOException x) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
x.toString());
}
return true;
}
}
But in my case, i do not want another java file to be created and instead i want to generate a class file directly. How to create a class file? Should i use a dynamic compiler to compile this source in string to create the class? In that scenario, i can directly store the class files in the file system. What is the usage of processingEnv.getFiler().createClassFile() method?
I tried googling around, but could never find an example using this method.
Filer.createClassFile(..)is broken in JDK 1.8 (build 1.8.0_121-b13). I have tested using it in many ways, and it never worked. Nevertheless, such functionality would be useful to copy previously generated files, instead of making statements to generate the source.