此时,我正试图创建一种通知程序,在附加说明的类别中形成一种称为“敲诈”的方法。 为此,我设立了以下职位:
package ro.Gabriel.AnnotationTest;
import com.google.auto.service.AutoService;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;
@AutoService(javax.annotation.processing.Processor.class)
@SupportedAnnotationTypes("ro.Gabriel.AnnotationTest.CustomGetter")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class CustomGetterProcessor extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(CustomGetter.class)) {
if (element.getKind() == ElementKind.CLASS) {
generateGetValueMethod((TypeElement) element);
}
}
return true;
}
private void generateGetValueMethod(TypeElement classElement) {
String className = classElement.getSimpleName().toString();
String packageName = processingEnv.getElementUtils().getPackageOf(classElement).getQualifiedName().toString();
String generatedClassName = className + "Generated";
String generatedCode = String.format(
"package %s;
" +
"public class %s {
" +
" public String getValue() {
" +
" return "Hello from getValue method!";
" +
" }
" +
"}
",
packageName, generatedClassName
);
try {
JavaFileObject fileObject = processingEnv.getFiler().createSourceFile(
packageName + "." + generatedClassName, classElement);
try (PrintWriter writer = new PrintWriter(fileObject.openWriter())) {
writer.print(generatedCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里是:
package ro.Gabriel.AnnotationTest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface CustomGetter { }
In the resources folder I created the following directory: META-INF/services
in the file resources/META-INF/services
I created the following file: javax.annotation.processing.Processor
http://www.un.org。 我增加了我的处理器:ro.Gabriel.Annotation.CustomGettercessor
。
在<代码>pom.xml上,文件一增加了<代码>@Autoservice(Processor.class)的以下存放处:
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>1.0.1</version>
<scope>provided</scope>
</dependency>
现在我设立了以下类别:
package ro.Gabriel.AnnotationTest;
@CustomGetter
public class ExampleClass {
}
ExampleClass e = new ExampleClass();
String value = e.getValue();// this method is not in the ExampleClass class even if it is annotated with @CustomGetter
我的问题是,为什么在例类动物中不出现<代码>getValue()方法?
我认为,必须在<代码>m.xml上建立某些组合,但我不知道如何。
谁能帮助我?
Thanks!