Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write an XmlAdapter so that a java.time.LocalDate field is written as 2026-11-04 and read back, and show how it is applied.

We write a class LocalDateAdapter extends XmlAdapter<String, LocalDate> whose unmarshal() calls LocalDate.parse(v) and whose marshal() returns v.toString(), both passing null through, because ISO dates like 2026-11-04 are exactly what LocalDate reads and writes. We apply it with @XmlJavaTypeAdapter(LocalDateAdapter.class) on the field, or once in package-info.java for every LocalDate in the package. Adapters need a no-argument constructor unless we register an instance with marshaller.setAdapter(), and a parse failure inside an adapter becomes a validation event, so we set an event handler that does not let it pass silently.

Why this question is asked

Modern Java code uses java.time everywhere, but JAXB's standard type mapping predates it, and many runtimes still do not map LocalDate out of the box; they either fail or write an empty element. The XmlAdapter is JAXB's general tool for this: it converts a type JAXB does not know into one it does. Interviewers ask for the LocalDate adapter because it is short enough to write live and it touches every important detail: generic parameters, null handling, where to apply it, and what happens on bad input. In this answer, we will see the problem, write the adapter, apply it at field and package level, and handle errors properly.

1The Problem Without an Adapter

JAXB maps a list of standard Java types to XML Schema types: strings, numbers, booleans, BigDecimal, the older java.util.Date and Calendar, and XMLGregorianCalendar. java.time types were added to Java later and are not part of that standard list. Depending on the runtime, a LocalDate field either produces an empty element, because JAXB treats LocalDate as a bean with no mappable properties, or fails because LocalDate has no no-argument constructor (check your runtime's behaviour).

Java
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Shipment {
private LocalDate shipDate = LocalDate.of(2026, 11, 4);
}
// marshal(new Shipment()) with no adapter, in many runtimes:
// <shipment><shipDate/></shipment> the date is lost

Neither outcome is acceptable, and the empty element is the worse one because nothing fails. We need to tell JAXB how to turn a LocalDate into text and back.

2Writing the Adapter

XmlAdapter<ValueType, BoundType> has two type parameters. BoundType is the type in our Java class, here LocalDate. ValueType is a type JAXB already knows how to write, here String. JAXB calls marshal() to convert our value before writing, and unmarshal() to convert what it read before setting the field.

Java
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import java.time.LocalDate;
public class LocalDateAdapter extends XmlAdapter<String, LocalDate> {
@Override
public LocalDate unmarshal(String v) {
return v == null ? null : LocalDate.parse(v.trim()); // "2026-11-04" -> 2026-11-04
}
@Override
public String marshal(LocalDate v) {
return v == null ? null : v.toString(); // 2026-11-04 -> "2026-11-04"
}
}
Step throughWhere JAXB calls the adapter
Our objectJAXB runtimeLocalDateAdapterXML text
read field shipDate (LocalDate)
marshal(2026-11-04)
"2026-11-04"
write <shipDate>2026-11-04</shipDate>
read text "2026-11-04"
unmarshal("2026-11-04")
LocalDate 2026-11-04
set field shipDate

8 messages in order. Play them, or step through them one at a time.

JAXB only ever sees the String; the adapter owns the conversion in both directions.

The null checks matter. When a field is null, JAXB may still call marshal() and expects null back, which means 'write nothing'. When an element is missing, unmarshal() is usually not called, but an empty or nil element can produce a null or empty string, and LocalDate.parse(null) would throw a NullPointerException. The trim() makes us tolerant of whitespace around the value, which XML often has when documents are pretty-printed.

LocalDate.toString() always writes the ISO-8601 form yyyy-MM-dd, and LocalDate.parse() reads exactly that form, which is also the lexical form of xs:date in XML Schema without a time zone. So the pair is symmetric with no formatter needed. If a partner used another format, such as 04.11.2026, we would use a DateTimeFormatter constant in both methods instead.

3Applying the Adapter

The direct way is to annotate the field. JAXB then uses the adapter for that field only.

Java
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Shipment {
@XmlJavaTypeAdapter(LocalDateAdapter.class)
private LocalDate shipDate;
@XmlJavaTypeAdapter(LocalDateAdapter.class)
private LocalDate deliveryDate;
}
// <shipment><shipDate>2026-11-04</shipDate><deliveryDate>2026-11-06</deliveryDate></shipment>
// package-info.java: one declaration for every LocalDate in the package
@XmlJavaTypeAdapter(value = LocalDateAdapter.class, type = LocalDate.class)
package com.acme.shipping.xml;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.time.LocalDate;

The package-level form needs the type attribute, which says which Java type the adapter is for, because it is not attached to any particular field. With it, every LocalDate field in the package's classes is adapted automatically, and nobody can forget the annotation on a new field. When there are several adapters for a package, they are grouped with @XmlJavaTypeAdapters. If the XSD is generated from these classes, we can add @XmlSchemaType(name = "date") on the field so the schema says xs:date instead of xs:string.

4Constructors and Adapter Instances

JAXB creates adapter instances itself, by reflection, so an adapter must have a public no-argument constructor. That is fine for our stateless LocalDateAdapter. But sometimes an adapter needs configuration, such as a formatter chosen per partner, or a lookup service to turn codes into objects. For that case we create the adapter ourselves and register it on the marshaller or unmarshaller before use.

Java
Unmarshaller u = ctx.createUnmarshaller();
u.setAdapter(new PartnerDateAdapter(DateTimeFormatter.ofPattern("dd.MM.yyyy")));
// JAXB now uses this instance for every @XmlJavaTypeAdapter(PartnerDateAdapter.class)

setAdapter() works per marshaller or unmarshaller, so the configured instance applies only to the operations that use it.

5Handling Bad Input

What happens when the partner sends <shipDate>2026-13-45</shipDate>? LocalDate.parse() throws a DateTimeParseException. JAXB does not let that exception escape directly; it reports it as a validation event to the ValidationEventHandler of the unmarshaller. Depending on the runtime and the handler, unmarshalling may continue with the field left null, which is a nasty surprise: a shipment with no date and no error. So for adapters doing real conversion, we set an event handler that fails, or that records the problem.

Java
Unmarshaller u = ctx.createUnmarshaller();
u.setEventHandler(event -> {
log.warn("XML problem at line {}: {}", event.getLocator().getLineNumber(), event.getMessage());
return false; // false: stop unmarshalling with an exception
});
u.unmarshal(new StringReader("<shipment><shipDate>2026-13-45</shipDate></shipment>"));
// XML problem at line 1: Text '2026-13-45' could not be parsed: Invalid value for MonthOfYear ...
// UnmarshalException thrown

Returning true from the handler instead means 'continue', which is right when we want to collect every problem in a document before rejecting it. Either way, the bad value is now visible instead of silently becoming null.

6Follow-up questions

Why not just use XMLGregorianCalendar?

It is JAXB's built-in date type and maps xs:date natively, but it is mutable, awkward to use and leaks an XML type into our model. Generated classes often use it; a binding file can tell xjc to use our LocalDateAdapter instead, so the generated fields are LocalDate.

How would you map LocalDateTime or OffsetDateTime?

The same pattern with a different type: XmlAdapter<String, OffsetDateTime> using OffsetDateTime.parse() and toString(), which match the xs:dateTime form with an offset. For LocalDateTime, be careful: xs:dateTime values often carry a time zone, and dropping it can shift times, so OffsetDateTime is usually the safer choice.

Can the adapter be tested without JAXB?

Yes, and it should be: new LocalDateAdapter().unmarshal("2026-11-04") and marshal(LocalDate.of(2026, 11, 4)) are plain method calls. A second test marshals a small class to check that the adapter is actually applied.

7Conclusion

In this answer, we wrote a LocalDateAdapter extending XmlAdapter<String, LocalDate>, with null-safe unmarshal() using LocalDate.parse() and marshal() using toString(), which together read and write ISO dates like 2026-11-04. We applied it with @XmlJavaTypeAdapter on a field or at package level in package-info.java with the type attribute, saw that adapters need a no-argument constructor unless we register an instance with setAdapter(), and set a ValidationEventHandler so a parse error in the adapter cannot silently leave a field null.

What to say in the interviewAbout 80 seconds aloud

Open with

JAXB has no standard mapping for java.time types, so in many runtimes a LocalDate field comes out empty or fails. I would write a LocalDateAdapter that extends XmlAdapter of String and LocalDate.

Then, if they want more

The first type parameter is what JAXB writes, the second is the type in my class. unmarshal returns null for null, otherwise LocalDate.parse of the trimmed string, and marshal returns null for null, otherwise toString. LocalDate's toString and parse both use ISO yyyy-MM-dd, which is the xs:date form, so 2026-11-04 round-trips without a formatter.

I apply it with @XmlJavaTypeAdapter of LocalDateAdapter.class on the field, or once in package-info.java with type equals LocalDate.class so every LocalDate in the package is covered and nobody forgets it.

JAXB instantiates adapters by reflection, so they need a no-argument constructor; if an adapter needs configuration, like a partner's date pattern, I create it myself and call setAdapter on the marshaller or unmarshaller.

Finally, errors: if parsing throws, JAXB turns it into a validation event, and depending on the handler the field can end up null silently, so I set a ValidationEventHandler that logs the line and returns false to fail, or collects the events if I want all errors at once.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write an XmlAdapter so that a java.time.LocalDate field is written as 2026-11-04 and...": https://scrivio-interview-library.netlify.app/java/jaxb/ae058097ae/