Stefan Filipovic
Stefan Filipovic

Reputation: 31

Java custom annotation default value to be equal to class field name

I have the following custom annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomAnnotation {
    public String value() default "";
}

and the following class:

public class CustomClass {
    @CustomAnnotation
    private String name;
}

Is it possible to set the CustomAnnotation's default value() to be equal to field variable name in specified class, instead of being hardcoded to an empty String as in this example - that is, to adapt dynamically when applied to a certain field in Class, unless explicitly specified otherwise? E.g. in this case it would be "name" in CustomClass.

Upvotes: 3

Views: 5315

Answers (1)

Link182
Link182

Reputation: 839

You can obtain field name when process annotation. Annotation can be processed in 2 ways: with reflection or annotation processor.

here is an example how to process with refletion:

List<String> names = Arrays.stream(myClassWithAnnotatedFields.getClass().getDeclaredFields())
                    .filter(field -> field.isAnnotationPresent(CustomAnnotation.class))
                    .map(Field::getName)
                    .collect(Collectors.toList())

here is an example how to process with 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());
    }
}

Upvotes: 3

Related Questions