3

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.

2
  • No, annotation values must be constants. At the place you process the annotation you could always reflectively get the field name if the value is "". Commented Mar 15, 2019 at 11:49
  • if you only use that annotation for that one field (or only for fields named name) sure Commented Mar 15, 2019 at 11:52

1 Answer 1

3

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());
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.