I have a question according to the API AnnotationProcessing. Here's a little Example.
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.FIELD)
public @interface MyAnnotation
{
String strNumberOne() default "";
String strNumberTwo() default "";
String strNumberThree() default "";
}
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv){
// I do not know how to beginn here
return true;
}
}
public class MyClass
{
@MyAnnotation(strNumberOne="one", strNumberTwo= "two")
private String strARandomString;
}
Now I want to read the fields declared in the annotation and if there's a field not declared my program should take the default-value.
I want to write the values in a list. At the end my list shoud look like that:
LinkedList<String> s = new LinkedList<>();
s.add(strNumberOne); // "one"
s.add(strNumberTwo); // "two"
s.add(strNumberThree); // (default) ""
How do I do this? I found a method that could help. It's in the Interface "Elements" the methods name is "getElementValuesWithDefaults()". But I don't know how to use it.. Also I want to know what's the difference betweens TypeElement and Element. I am thankful for every answer! :)
Best regards!
If
MyAnnotationis the annotation which your processor supports, then you'd just write something like this:The logic of the
shouldClaimmethod is explained by the documentation forprocess. It would be more complicated if your annotation supports e.g.*or a type of the formname.*, but in general you don't. (SeegetSupportedAnnotationTypesfor a description of what those mean.)If
MyAnnotationisn't the annotation which your processor supports, then you would need to go throughgetElementValuesWithDefaultsif it's a type declared in the package you're compiling. Because annotation processing happens during compilation, class files don't exist yet for the source files being compiled, which is why we use theElementAPI instead.Elementrepresents a declaration of some kind, for example a class, method or variable.TypeElementrepresents a class, interface, enum or annotation type declaration.TypeElementis similar toClassin terms of what we can do with it, except that we can use aTypeElementfor a class which is not necessarily compiled.To get annotation values through the element API, you'd do something like this:
That's a pain, but we only need to use the element API if the annotation we're interested in is one of the classes being compiled.
We might also want to find the
AnnotationMirrorand/orAnnotationValueto cause a message of some kind on a particular element using one of theMessager.printMessageoverloads which takes one of the aforementioned objects as an argument.