A
A
Alexiuscrow2015-08-23 05:18:46
Java
Alexiuscrow, 2015-08-23 05:18:46

How to replace code in an existing class using an annotation processor?

There are 2 annotations:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Ann {
    public String description() default "AAA";
    public String template() default "BBB";
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface AnotherAnn {
    public String text() default "Text";
}

There is a simple class in which the method is marked with one of the above annotations:
public class App {
    @Ann(description = "Yo!", template = "Bitches.")
    public void someMethod(){}
}

It is necessary to use the annotation processor to replace the @Ann annotation in the someMethod method of the App class with the @AnotherAnn annotation (or add the second one). And as a result, display the contents of the text parameter from the @AnotherAnn annotation:
@SupportedAnnotationTypes("alexiuscrow.annotation.Ann")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class Proc extends AbstractProcessor {

    public Proc() {
        super();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        /* TODO DIRTY WORK (ANNOTATION REPLACEMENT)*/

       Class<App> appClass = App.class;

        for (Method method: appClass.getDeclaredMethods()) {
            if (method.isAnnotationPresent(AnotherAnn.class)) {
                AnotherAnn anotherAnn = method.getAnnotation(AnotherAnn.class);

                System.out.println("Method: \t" + method.getName());
                System.out.println("AnotherAnn: \t" + anotherAnn);
                System.out.println("Text: \t" + anotherAnn.text());
            }
        }
        return true;
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question