简体   繁体   English

Java自定义注解默认值等于类字段名

[英]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?是否可以将 CustomAnnotation 的默认 value() 设置为等于指定类中的字段变量名称,而不是像本示例中那样硬编码为空字符串 - 即在应用于类中的某个字段时动态适应,除非另有明确规定? Eg in this case it would be "name" in CustomClass.例如,在这种情况下,它将是 CustomClass 中的“名称”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM