我有一組帶有典型 Java 驗證注釋(Hibernate 實作)的屬性,例如,
@Size(max = 10)
private String data;
我想知道是否Size's max可以通過編程方式訪問該值。
data這是在檢索時執行一些轉換操作所必需的。顯然,10可以硬編碼為最終的靜態類變數,但是有沒有辦法訪問這些注釋值?
uj5u.com熱心網友回復:
由于注解具有運行時保留,您可以通過反射訪問它。例如(忽略任何例外):
Field field = MyClass.class.getDeclaredField("data");
Size size = field.getAnnotation(Field.class);
int max = size.max();
如果要獲取觸發約束錯誤的值,請捕獲ConstraintViolationException. 然后,您可以從違規中獲取約束注釋。另一個例子:
// just some code to get a descriptor
ConstraintDescriptor<?> descriptor = constraintViolationException.getAnnotations().stream()
.map(ConstraintViolation::getConstraintDescriptor)
.findAny()
.orElseThrow();
// now its properties can be accessed
Map<String, Object> attributes = descriptor.getAttributes();
// attributes contains an entry with key "max" and value 10 for your @Size annotation
Size size = (Size) descriptor.getAnnotation();
int max = size.max();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/491104.html
上一篇:如何從回收站視圖中獲取字串值
