java - 获取包含 @Size 注释的字段名称及其最大长度
问题描述
我有这个实体 -
@Entity
public class Employee{
@Id
@NotNull
@Size(max=5)
private Integer employeeId;
@NotNull
@Size(max=40)
private String employeeName;
private Long employeeSalary;
}
我想获取字段的名称以及允许的最大长度。也就是说,对于上述情况,输出应该是
employeeId - 5
employeeName - 40
我创建了以下内容,它返回包含 @Size 的字段的名称
public boolean hasSize() {
return Arrays.stream(this.getClass().getDeclaredFields())
.anyMatch(field -> field.isAnnotationPresent(Size.class));
}
public List<String> getSizeFields(){
if(hasSize()) {
Stream<Field> filter = Arrays.stream(this.getClass().getDeclaredFields())
.filter(field -> field.isAnnotationPresent(Size.class));
return filter.map(obj -> obj.getName()).collect(Collectors.toList());
}
else
return null;
}
建议我如何获得字段的最大长度。
解决方案
Map<String, Integer> map = Stream.of(e.getClass().getDeclaredFields())
.filter(f -> f.isAnnotationPresent(Size.class))
.collect(Collectors.toMap(
f -> f.getName(),
f -> f.getAnnotation(Size.class).max()));
推荐阅读
- html - 当我的弹出窗口处于活动状态时如何禁用页面背景上的滚动条
- php - 带有新 Swift_Mailer 的 Laravel Mailer 在 Gmail 中显示为错误的发件人域
- java - 看不出我的kafka服务器在一段时间内突然停止的原因
- python - base_library.zip 无法解压!fopen 权限被拒绝
- mysql - Kafka 到数据库数据流水线
- c# - 自动保存文件而不提示在网络浏览器中保存文件
- javascript - 连接到服务器的 NODE JS Socket.io 错误
- python - Pandas 通过拆分可选的前导非字符串字符来计算新列
- python - 如何使用 Python PIL 粘贴到特定位置?
- java - 如何在另一个路径中加载 application.properties 文件?