Java custom annotation defaults are equal to class field names … here is a solution to the problem.
Java custom annotation defaults are equal to class field names
I have the following custom note:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomAnnotation {
public String value() default "";
}
and the following classes:
public class CustomClass {
@CustomAnnotation
private String name;
}
Is it possible to set CustomAnnotation’s default value() equal to the field variable name in the specified class, rather than being hard-coded as an empty string as in this case – that is, dynamically adapting to a field when applied to a field in the class, unless explicitly stated otherwise? For example. In this case, it will be the “name” in CustomClass.
Solution
Field
names are available when working with annotations. Annotations can be processed in two ways: using reflection or the annotation processor.
Here is an example of how to use reflection for processing:
List<String> names = Arrays.stream(myClassWithAnnotatedFields.getClass().getDeclaredFields())
.filter(field -> field.isAnnotationPresent(CustomAnnotation.class))
.map(Field::getName)
.collect(Collectors.toList())
Here is an example of how to handle it using the annotation processor:
import javax.annotation.processing.Processor;
import javax.annotation.processing.AbstractProcessor;
@com.google.auto.service.AutoService(Processor.class)
public class MyProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
List<Name> names = roundEnvironment.getElementsAnnotatedWith(CustomAnnotation.class)
.stream()
.map(Element::getSimpleName)
.collect(Collectors.toList());
}
}