0
# Bean Validation
1
2
Primary validation interface for validating JavaBean objects, properties, and values with comprehensive constraint violation reporting and property path navigation.
3
4
## Capabilities
5
6
### Validator Interface
7
8
Main interface for performing validation operations on objects, properties, and values.
9
10
```java { .api }
11
/**
12
* Primary interface for validating beans, properties, and values
13
* Implementations must be thread-safe and can be cached
14
*/
15
interface Validator {
16
/**
17
* Validate all constraints on the provided object
18
* @param object object to validate
19
* @param groups validation groups to apply (optional)
20
* @return set of constraint violations, empty if valid
21
* @throws IllegalArgumentException if object is null
22
*/
23
<T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups);
24
25
/**
26
* Validate constraints on a specific property of an object
27
* @param object object containing the property
28
* @param propertyName name of the property to validate
29
* @param groups validation groups to apply (optional)
30
* @return set of constraint violations for the property
31
* @throws IllegalArgumentException if object is null or propertyName is invalid
32
*/
33
<T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups);
34
35
/**
36
* Validate constraints on a property value without requiring an object instance
37
* @param beanType class of the bean containing the property
38
* @param propertyName name of the property
39
* @param value value to validate
40
* @param groups validation groups to apply (optional)
41
* @return set of constraint violations for the value
42
* @throws IllegalArgumentException if beanType is null or propertyName is invalid
43
*/
44
<T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups);
45
46
/**
47
* Get validation metadata for a class
48
* @param clazz class to get constraints for
49
* @return BeanDescriptor containing validation metadata
50
* @throws IllegalArgumentException if clazz is null
51
*/
52
BeanDescriptor getConstraintsForClass(Class<?> clazz);
53
54
/**
55
* Get ExecutableValidator for method and constructor validation
56
* @return ExecutableValidator instance
57
*/
58
ExecutableValidator forExecutables();
59
60
/**
61
* Unwrap the Validator to a specific implementation type
62
* @param type target type to unwrap to
63
* @return unwrapped validator instance
64
* @throws ValidationException if unwrapping is not supported
65
*/
66
<T> T unwrap(Class<T> type);
67
}
68
```
69
70
**Usage Examples:**
71
72
```java
73
import jakarta.validation.*;
74
import jakarta.validation.constraints.*;
75
import java.util.Set;
76
77
// Bean definition with constraints
78
class Person {
79
@NotNull
80
@Size(min = 2, max = 50)
81
private String name;
82
83
@Min(0)
84
@Max(150)
85
private int age;
86
87
88
private String email;
89
90
@Valid
91
private Address address;
92
93
// constructors, getters, setters...
94
}
95
96
// Validation examples
97
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
98
99
// 1. Validate entire object
100
Person person = new Person("", -5, "invalid-email");
101
Set<ConstraintViolation<Person>> violations = validator.validate(person);
102
103
for (ConstraintViolation<Person> violation : violations) {
104
System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
105
}
106
// Output:
107
// name: size must be between 2 and 50
108
// age: must be greater than or equal to 0
109
// email: must be a well-formed email address
110
111
// 2. Validate specific property
112
Set<ConstraintViolation<Person>> nameViolations =
113
validator.validateProperty(person, "name");
114
115
// 3. Validate value without object instance
116
Set<ConstraintViolation<Person>> emailViolations =
117
validator.validateValue(Person.class, "email", "test@example.com");
118
```
119
120
### Constraint Violation
121
122
Interface describing a single constraint violation with detailed information about the validation failure.
123
124
```java { .api }
125
/**
126
* Describes a constraint violation with detailed context information
127
* @param <T> type of the root bean
128
*/
129
interface ConstraintViolation<T> {
130
/**
131
* Get the interpolated error message for this constraint violation
132
* @return human-readable error message
133
*/
134
String getMessage();
135
136
/**
137
* Get the non-interpolated error message template
138
* @return message template with placeholders
139
*/
140
String getMessageTemplate();
141
142
/**
143
* Get the root bean being validated
144
* @return root bean instance or null if validating a class
145
*/
146
T getRootBean();
147
148
/**
149
* Get the class of the root bean
150
* @return root bean class
151
*/
152
Class<T> getRootBeanClass();
153
154
/**
155
* Get the leaf bean containing the constraint violation
156
* @return leaf bean instance
157
*/
158
Object getLeafBean();
159
160
/**
161
* Get method/constructor parameters when validating executables
162
* @return parameter array or null if not validating executables
163
*/
164
Object[] getExecutableParameters();
165
166
/**
167
* Get method/constructor return value when validating executables
168
* @return return value or null if not validating return values
169
*/
170
Object getExecutableReturnValue();
171
172
/**
173
* Get the property path from root bean to the constraint violation
174
* @return Path describing navigation from root to violated property
175
*/
176
Path getPropertyPath();
177
178
/**
179
* Get the value that failed validation
180
* @return invalid value
181
*/
182
Object getInvalidValue();
183
184
/**
185
* Get metadata about the violated constraint
186
* @return ConstraintDescriptor for the violated constraint
187
*/
188
ConstraintDescriptor<?> getConstraintDescriptor();
189
190
/**
191
* Unwrap the ConstraintViolation to a specific type
192
* @param type target type to unwrap to
193
* @return unwrapped instance
194
* @throws ValidationException if unwrapping is not supported
195
*/
196
<U> U unwrap(Class<U> type);
197
}
198
```
199
200
### Property Path Navigation
201
202
Interface for navigating property paths from root objects to constraint violations.
203
204
```java { .api }
205
/**
206
* Path from an object to another in an object graph
207
* Immutable and thread-safe
208
*/
209
interface Path extends Iterable<Path.Node> {
210
/**
211
* String representation of the path using dot notation
212
* @return path as string (e.g., "person.address.street")
213
*/
214
String toString();
215
216
/**
217
* Base interface for path nodes
218
*/
219
interface Node {
220
/**
221
* Get the name of this node (property name, method name, etc.)
222
* @return node name or null for certain node types
223
*/
224
String getName();
225
226
/**
227
* Check if this node represents an iterable element
228
* @return true if node is in an iterable (List, Set, etc.)
229
*/
230
boolean isInIterable();
231
232
/**
233
* Get the index if this node represents an indexed element
234
* @return index or null if not indexed
235
*/
236
Integer getIndex();
237
238
/**
239
* Get the key if this node represents a keyed element (Map)
240
* @return key or null if not keyed
241
*/
242
Object getKey();
243
244
/**
245
* Get the kind of element this node represents
246
* @return ElementKind enum value
247
*/
248
ElementKind getKind();
249
250
/**
251
* Cast this node to a specific node type
252
* @param nodeType target node type
253
* @return node cast to specified type
254
* @throws ClassCastException if cast is not valid
255
*/
256
<T extends Path.Node> T as(Class<T> nodeType);
257
}
258
259
/**
260
* Node representing a bean
261
*/
262
interface BeanNode extends Node {
263
/**
264
* Get the container element type index for container element nodes
265
* @return type argument index or null
266
*/
267
Integer getTypeArgumentIndex();
268
}
269
270
/**
271
* Node representing a property
272
*/
273
interface PropertyNode extends Node {
274
/**
275
* Get the container element type index for container element nodes
276
* @return type argument index or null
277
*/
278
Integer getTypeArgumentIndex();
279
}
280
281
/**
282
* Node representing a method
283
*/
284
interface MethodNode extends Node {
285
/**
286
* Get the parameter types of the method
287
* @return list of parameter types
288
*/
289
List<Class<?>> getParameterTypes();
290
}
291
292
/**
293
* Node representing a constructor
294
*/
295
interface ConstructorNode extends Node {
296
/**
297
* Get the parameter types of the constructor
298
* @return list of parameter types
299
*/
300
List<Class<?>> getParameterTypes();
301
}
302
303
/**
304
* Node representing a method return value
305
*/
306
interface ReturnValueNode extends Node {
307
/**
308
* Get the container element type index for container element nodes
309
* @return type argument index or null
310
*/
311
Integer getTypeArgumentIndex();
312
}
313
314
/**
315
* Node representing a method/constructor parameter
316
*/
317
interface ParameterNode extends Node {
318
/**
319
* Get the parameter index
320
* @return parameter index
321
*/
322
int getParameterIndex();
323
324
/**
325
* Get the container element type index for container element nodes
326
* @return type argument index or null
327
*/
328
Integer getTypeArgumentIndex();
329
}
330
331
/**
332
* Node representing cross-parameter constraints
333
*/
334
interface CrossParameterNode extends Node {}
335
336
/**
337
* Node representing a container element
338
*/
339
interface ContainerElementNode extends Node {
340
/**
341
* Get the container element type index
342
* @return type argument index
343
*/
344
Integer getTypeArgumentIndex();
345
}
346
}
347
```
348
349
### Constraint Violation Exception
350
351
Exception containing constraint violations, typically thrown by frameworks when validation fails.
352
353
```java { .api }
354
/**
355
* Exception containing constraint violations
356
* Typically thrown by frameworks when validation fails in certain contexts
357
*/
358
class ConstraintViolationException extends ValidationException {
359
/**
360
* Create exception with a set of constraint violations
361
* @param constraintViolations set of violations
362
*/
363
ConstraintViolationException(Set<? extends ConstraintViolation<?>> constraintViolations);
364
365
/**
366
* Create exception with message and constraint violations
367
* @param message exception message
368
* @param constraintViolations set of violations
369
*/
370
ConstraintViolationException(String message, Set<? extends ConstraintViolation<?>> constraintViolations);
371
372
/**
373
* Get the constraint violations
374
* @return unmodifiable set of constraint violations
375
*/
376
Set<ConstraintViolation<?>> getConstraintViolations();
377
}
378
```
379
380
**Usage Examples:**
381
382
```java
383
// Working with constraint violations
384
Set<ConstraintViolation<User>> violations = validator.validate(user);
385
386
if (!violations.isEmpty()) {
387
for (ConstraintViolation<User> violation : violations) {
388
// Get violation details
389
Path propertyPath = violation.getPropertyPath();
390
Object invalidValue = violation.getInvalidValue();
391
String message = violation.getMessage();
392
393
// Navigate path nodes
394
for (Path.Node node : propertyPath) {
395
System.out.println("Node: " + node.getName() +
396
", Kind: " + node.getKind() +
397
", Index: " + node.getIndex());
398
}
399
400
// Get constraint metadata
401
ConstraintDescriptor<?> descriptor = violation.getConstraintDescriptor();
402
System.out.println("Constraint: " + descriptor.getAnnotation().annotationType().getSimpleName());
403
}
404
}
405
406
// Handling exceptions
407
try {
408
// Some framework operation that validates
409
someFrameworkMethod(invalidObject);
410
} catch (ConstraintViolationException e) {
411
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
412
// Handle violations...
413
}
414
```