public @interface CustomAnnotation { String value(); } @SupportedAnnotationTypes("CustomAnnotation") @SupportedSourceVersion(SourceVersion.RELEASE_8) public class CustomAnnotationProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { String code = generateCode(element); insertCode(element, code); } } return true; } private String generateCode(Element element) { CustomAnnotation annotation = element.getAnnotation(CustomAnnotation.class); String value = annotation.value(); return String.format("System.out.println(\"%s\");", value); } private void insertCode(Element element, String code) { // ... } } <build> <plugins> <plugin> <groupId>org.bsc.maven</groupId> <artifactId>maven-processor-plugin</artifactId> <configuration> <processors> <processor>com.example.CustomAnnotationProcessor</processor> </processors> </configuration> <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>alchemy-annotations</artifactId> <version>1.0.0</version> </dependency> </dependencies> </plugin> </plugins> </build> @CustomAnnotation("Hello, Alchemy Annotations!") public class MyClass { // ... } shell mvn clean compile


上一篇:
下一篇:
切换中文