2015-12-17 102 views
0

我正在使用來自Java Hibernate的Validation註釋在我的項目中。我想驗證我收到的數據並返回一組無效字段。那可能嗎?Java Hibernate驗證返回無效字段

比方說,我有一個Java類名爲Car

public class Car { 

    @NotNull 
    private String manufacturer; 

    @NotNull 
    @Size(min = 2, max = 14) 
    @CheckCase(CaseMode.UPPER) 
    private String licensePlate; 

    @Min(2) 
    private int seatCount; 

    public Car (String manufacturer, String licencePlate, int seatCount) { 
     this.manufacturer = manufacturer; 
     this.licensePlate = licencePlate; 
     this.seatCount = seatCount; 
    } 

    //getters and setters ... 
} 

比方說,我創建了一個新的汽車:

Car c = new Car("AUDI", NULL, 1); 

這不應該是可能的,因爲車牌應填寫和座位的數量應該大於或等於2.因此,我想返回一個包含兩個元素的數組,表示車牌和座位數量無效(如果可能,附加信息)。

+0

你無法將代碼添加到您的汽車初始化函數,來測試和處理這些情況? – ElmerCat

+0

也許問題不清楚。我想驗證我創建的汽車並返回一組無效的字段 – STheFox

回答

1

由於ElmerCat指出,構造函數應該被定義爲:

public Car (
    @NotNull String manufacturer, 
    @NotNull @Size(min = 2, max = 14) @CheckCase(CaseMode.UPPER) String licensePlate, 
    @Min(2) int seatCount) { 
    this.manufacturer = manufacturer; 
    this.licensePlate = licensePlate; 
    this.seatCount = seatCount; 
}