我正在玩java注释处理,以学习如何在编译时生成java代码。我创建了一个抽象处理器(使用javapoet)创建一个新类。但是我无法让它发挥作用。 我在一个java类中压缩了这个例子。 我做错了什么?
当我编译项目时,我得到:
Error:java: Bad service configuration file, or exception thrown while constructing Processor object: javax.annotation.processing.Processor: Provider com.mateuyabar.AnnotProc not found
这是java代码:
package com.mateuyabar;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
@AutoService(Processor.class)
public class AnnotProc extends AbstractProcessor{
public @interface MyAnnotation {}
@MyAnnotation
public static void dummyForAnnotation(){}
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment env) {
for(Element el:env.getElementsAnnotatedWith(MyAnnotation.class)){
System.out.println(el.asType());
}
MethodSpec sampleMethod = MethodSpec.methodBuilder("sampleMethod").addModifiers(Modifier.PUBLIC).returns(String.class).addParameter(String.class, "param1")
.addStatement("return $S+$N", "Welcome, ", "name").build();
TypeSpec customerService = TypeSpec.classBuilder("MyGeneratedClass").addModifiers(Modifier.PUBLIC).addMethod(sampleMethod).build();
JavaFile javaFile = JavaFile.builder("com.mateuyabar", customerService).build();
try {
javaFile.writeTo(System.out);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton(MyAnnotation.class.getName());
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
public static void main(String[] args){
System.out.println(new com.mateuyabar.MyGeneratedClass().sampleMethod("a"));
}
}