我正在研究一个应该从 Annotations 生成 java 代码的小库。
public class MyAnnotationProcessor extends AbstractProcessor {
/**
* This suffix will be appended on every {@link OrmAble}
*/
public static final String CLASS_SUFFIX = "Helper";
private Elements elementUtils;
private Types typeUtils;
private Filer filer;
@Override
public synchronized void init(ProcessingEnvironment env) {
super.init(env);
elementUtils = env.getElementUtils();
typeUtils = env.getTypeUtils();
filer = env.getFiler();
}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
System.out.println("Start AnnotationProcessing");
for (Element elem : roundEnv
.getElementsAnnotatedWith(MyAnnotation.class)) {
if (elem instanceof TypeElement)
createCode((TypeElement) elem);
}
// no further processing of this annotation type
return true;
}
private void createCode(TypeElement typeElement) {
// Write the view injector class.
try {
JavaFileObject jfo = filer.createSourceFile(
getPackageName(typeElement) + typeElement.getSimpleName()
+ CLASS_SUFFIX, typeElement);
Writer writer = jfo.openWriter();
brewJavaCode(writer, typeElement);
writer.flush();
writer.close();
} catch (IOException e) {
error(typeElement, "Unable to write injector for type %s: %s",
typeElement, e.getMessage());
} catch (ClassNotFoundException e) {
error(typeElement, "Class "
+ typeElement.getQualifiedName().toString() + " not found");
}
}
}
我使用 maven 来构建它,但是注释并编写了一些单元测试,其中包含一些用 MyAnnotation 注释的类。
我的 pom.xml 文件如下所示:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
<executions>
<execution>
<id>default-compile</id>
<goals><goal>compile</goal></goals>
<configuration>
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</execution>
<execution>
<id>default-test-compile</id>
<goals><goal>testCompile</goal></goals>
<configuration>
<annotationProcessors>
<annotationProcessor>com.example.MyAnnotationProcessor</annotationProcessor>
</annotationProcessors>
</configuration>
</execution>
</executions>
</plugin>
我还尝试在 Eclipse 中使用带注释的类运行测试。我从我的库中生成了一个 jar,并将其设置为 Eclipse 中的 AnnotationProcessor。但是永远不会执行注释处理。
据我所知,生成的类文件应该放在 target/right 或者生成的 java 文件将存储在哪里?
JavaFileObject jfo = filer.createSourceFile(
getPackageName(typeElement) + typeElement.getSimpleName()
+ CLASS_SUFFIX, typeElement);
有什么建议可能是错的吗?