我正在研究一个应该从注释生成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 /右边,或者将生成的java文件存储在哪里?
JavaFileObject jfo = filer.createSourceFile(
getPackageName(typeElement) + typeElement.getSimpleName()
+ CLASS_SUFFIX, typeElement);
任何建议可能有什么问题吗?
包含AP完全限定名称的javax.annotation.processing.Processor
在META-INF/services
下注册
getSupportedAnnotationTypes()
,该函数应返回要处理的所需Annotations
的列表。classPath
中至少有一个班级正在使用所需的注释之一。这是由于Java compiler
优化,其方式是仅在