私はこの実体を持っています-
@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()));
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加