首页 > 解决方案 > 获取包含 @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;
    }

建议我如何获得字段的最大长度。

标签: javajava-8annotationsjava-stream

解决方案


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

推荐阅读