首页 > 解决方案 > Java自定义注解默认值等于类字段名

问题描述

我有以下自定义注释:

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

和以下课程:

public class CustomClass {
    @CustomAnnotation
    private String name;
}

是否可以将 CustomAnnotation 的默认 value() 设置为等于指定类中的字段变量名称,而不是像本例中那样硬编码为空字符串 - 也就是说,当应用于 Class 中的某个字段时动态适应,除非另有明确说明?例如,在这种情况下,它将是 CustomClass 中的“名称”。

标签: java

解决方案


处理注解时可以获取字段名。可以通过两种方式处理注释:使用反射或注释处理器。

这是一个如何使用反射进行处理的示例:

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

这是一个如何使用注释处理器进行处理的示例:

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());
    }
}

推荐阅读