Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

JAXB%20Interview%20Questions%20and%20Answers

Question: How to validate java objects?
Answer: • The graph of Java objects can contain invalid data
– could occur when objects created by unmarshalling are modified
– could occur when objects are created from scratch
• Use a Validator to validate the objects
• Example
Validator v = factory.createValidator();
try {
v.validateRoot(cars);
v.validate(car);
} catch (ValidationException e) {
// Handle the validation error described by e.getMessage().
}

• Other Validator methods
– boolean setEventHandler(ValidationEventHandler handler)
• handleEvent method of ValidationEventHandler is called
if validation errors are encountered
• default handler terminates marshalling after first error
• return true to continue validating
• return false to terminate with ValidationException

Pass an instance of javax.xml.bind.util.ValidationEventCollector
(in jaxb-api.jar) to setEventHandler to collect validation errors and
query them later instead of handling them during validation.
ValidationEventCollector vec =
new ValidationEventCollector();
v.setEventHandler(vec);
v.validate(cars);
ValidationEvent[] events = vec.getEvents();
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook