1.

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();

The graph of Java objects can contain invalid data:

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

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();



Discussion

No Comment Found