java - 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 中的“名称”。
解决方案
处理注解时可以获取字段名。可以通过两种方式处理注释:使用反射或注释处理器。
这是一个如何使用反射进行处理的示例:
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());
}
}
推荐阅读
- python-3.x - 在 Python 中执行每个子类函数之前调用父类函数
- android - 更换工具栏后汉堡图标未正确显示
- javascript - 如何使用 Hooks 在 React Component 中重新启动音频
- excel - 如果满足条件,将行从一个工作簿复制到另一个工作簿
- python - 在每行之后迭代两个列表切换方向的更多pythonic方式?
- c++ - 广度优先搜索段错误
- .net - ASP.NET Core 中的 dotnet-trace 不显示控制器的任何方法
- c - 用 calloc 创建的以空字符结尾的字符串?
- javascript - 为什么 XSS 在创建的 HTML 页面上不起作用?
- node.js - AWS Beanstalk - 在部署时,从 S3 存储桶复制带有 env 变量的文件?