Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Your XML contract represents money as <amount currency="EUR">12.50</amount>, but your domain uses an immutable Money record without a no-argument constructor. How would you map it with JAXB?

I would not bind the Money record directly. Instead I create a small mutable class, for example AmountXml, with @XmlValue BigDecimal value and @XmlAttribute String currency, which JAXB maps naturally to <amount currency="EUR">12.50</amount>, and an XmlAdapter<AmountXml, Money> that converts between it and the record. Records work poorly with JAXB because it expects a no-argument constructor and settable fields, so the adapter keeps the domain immutable, and it is also the place to make scale and rounding rules explicit and to test round trips, including zero and negative amounts.

Why this question is asked

Money is one of those values every domain wants to model properly: an immutable type that always has a currency, can never be half-built and has no setters. XML contracts, on the other hand, are written for tools that build objects field by field. Interviewers ask this design question to see whether we can bridge the two without weakening the domain model, and whether we think about precision, which is where money bugs actually happen. In this answer, we will see why the record does not bind directly, design the adapted type, write the adapter, decide the precision rules, and test it.

1Why the Record Does Not Bind Directly

Here is the domain type. It is a record, so it is immutable, has a canonical constructor that validates its fields, and has no setters and no no-argument constructor.

Java
public record Money(BigDecimal amount, Currency currency) {
public Money {
Objects.requireNonNull(amount);
Objects.requireNonNull(currency);
if (amount.scale() > currency.getDefaultFractionDigits())
throw new IllegalArgumentException("too many decimals for " + currency);
}
}
@XmlRootElement
class Payment { Money amount; }
JAXBContext.newInstance(Payment.class);
// fails in common runtimes: Money does not have a no-arg default constructor (check your runtime)

JAXB's unmarshalling model is to create an empty object and then set its properties one by one as it reads them. A record allows neither: there is no empty state, and its fields are final. Some runtimes have added partial support for records, but relying on it ties us to one runtime and still does not give us control over the XML shape (check your runtime). The question also wants a specific shape: the currency as an attribute and the number as the element's text, which needs annotations the record should not carry.

2Designing the Adapted Type

The adapted type is a plain class that exists only for XML. @XmlValue maps a property to the text content of the element, and @XmlAttribute maps another to an attribute. A class with @XmlValue may have attributes but no child elements, which is exactly the shape <amount currency="EUR">12.50</amount>.

Java
@XmlAccessorType(XmlAccessType.FIELD)
public class AmountXml {
@XmlValue
BigDecimal value;
@XmlAttribute(name = "currency", required = true)
String currency;
public AmountXml() {} // for JAXB
AmountXml(BigDecimal value, String currency) { this.value = value; this.currency = currency; }
}

Notice that AmountXml is deliberately dumb: no validation, mutable fields, a public no-argument constructor. That is what makes it easy for JAXB, and it is safe because no code outside the adapter ever sees it.

3Writing the Adapter

XmlAdapter<AmountXml, Money> converts between the XML-friendly type and the record. JAXB writes and reads AmountXml; our classes only hold Money.

Java
public class MoneyAdapter extends XmlAdapter<AmountXml, Money> {
@Override
public Money unmarshal(AmountXml x) {
if (x == null) return null;
Currency c = Currency.getInstance(x.currency); // "EUR", or IllegalArgumentException
BigDecimal v = x.value.setScale(c.getDefaultFractionDigits()); // 12.5 -> 12.50; 12.505 -> ArithmeticException
return new Money(v, c);
}
@Override
public AmountXml marshal(Money m) {
if (m == null) return null;
return new AmountXml(m.amount(), m.currency().getCurrencyCode());
}
}
@XmlRootElement(name = "payment")
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymentXml {
@XmlElement(name = "amount")
@XmlJavaTypeAdapter(MoneyAdapter.class)
private Money amount;
}
// marshal: <payment><amount currency="EUR">12.50</amount></payment>
// unmarshal of the same text gives Money[amount=12.50, currency=EUR]
Step throughThree layers for one value
  1. XML text<amount currency="EUR">12.50</amount>
  2. AmountXmlmutable, @XmlValue value and @XmlAttribute currency
  3. MoneyAdapterconverts, validates, applies scale rules
  4. Money recordimmutable domain value used everywhere else

4 layers, from the top down. Step through them one at a time.

Only the adapter knows both the XML-friendly type and the domain type.

4Making Precision Rules Explicit

Money bugs are almost always precision bugs, and the adapter is the boundary where they enter. Notice that unmarshal() uses setScale() without a rounding mode. That means 12.5 becomes 12.50, which is safe, but 12.505 throws an ArithmeticException rather than being silently rounded. That is a deliberate choice: an amount with too many decimals is probably a partner error, and rounding it could move money without anyone noticing. If the contract says amounts must be rounded, we write setScale(2, RoundingMode.HALF_EVEN) and document that rule in the adapter.

Other rules belong here too. We always use BigDecimal, never double, because binary floating point cannot represent 0.1 exactly. The currency decides the scale: euros have 2 decimals, Japanese yen 0, and some currencies 3, which Currency.getDefaultFractionDigits() tells us. And on output, BigDecimal.toString() can switch to scientific notation for some values, such as 1E+3, which most partner schemas reject; if our values could have such a form, marshal() should write value.toPlainString() through a String-typed @XmlValue instead.

Edge cases the adapter must handle
InputResultWhy
12.5 EURMoney 12.50 EURscale raised to the currency's 2 digits
12.505 EURArithmeticExceptionno silent rounding of a partner's amount
0 EURMoney 0.00 EURzero is valid and keeps its scale
-3.20 EURMoney -3.20 EURrefunds and corrections are negative
1000 JPYMoney 1000 JPYyen has 0 decimals
12.50 XYZIllegalArgumentExceptionunknown currency code

5Testing Round Trips

We test the adapter at two levels. Unit tests call marshal() and unmarshal() directly with the edge cases in the table, and check exceptions for the invalid ones. Then a round-trip test marshals a PaymentXml to text, checks the exact string, and unmarshals it back, asserting that the resulting Money equals the original. Because records implement equals() from their fields, and BigDecimal.equals() compares scale too, a round trip that turned 12.50 into 12.5 would fail the test, which is exactly what we want.

Java
@ParameterizedTest
@CsvSource({"12.50,EUR", "0.00,EUR", "-3.20,EUR", "1000,JPY"})
void roundTrip(String amount, String ccy) throws Exception {
Money original = new Money(new BigDecimal(amount), Currency.getInstance(ccy));
String xml = toXml(new PaymentXml(original));
assertThat(xml).contains("<amount currency=\"" + ccy + "\">" + amount + "</amount>");
assertThat(fromXml(xml).amount()).isEqualTo(original); // equal, including scale
}

6Follow-up questions

Why not add a private no-argument constructor to Money?

A record cannot have fields set after construction, so even with an extra constructor JAXB could not fill it in. Turning Money into a mutable class just for XML would weaken the whole domain to satisfy one integration.

Where should the validation errors go?

An exception in an adapter is reported to the unmarshaller's ValidationEventHandler. We set a handler that fails on errors, or collects them with their line numbers, so a bad amount rejects the message with a clear reason instead of leaving a null amount.

Could MOXy or another runtime map records directly?

Some runtimes have experimented with record support, but behaviour differs and the XML shape still needs annotations on the record. The adapter approach works the same on every JAXB runtime, which matters for long-lived integrations.

7Conclusion

In this answer, we saw that an immutable Money record does not fit JAXB's model of creating an empty object and setting fields, so we introduced a mutable AmountXml with @XmlValue for the number and @XmlAttribute for the currency, and a MoneyAdapter that converts it to and from the record. The adapter is also where precision rules live: BigDecimal only, scale from the currency, no silent rounding unless the contract says so, and plain number output. Finally, we tested round trips including zero, negative and invalid amounts.

What to say in the interviewAbout 80 seconds aloud

Open with

I would keep the Money record as it is and put the XML shape on a separate, mutable adapted type. JAXB unmarshals by creating an empty object and setting properties, and a record has no empty state and final fields, so direct binding either fails or ties me to one runtime's record support.

Then, if they want more

The adapted type, say AmountXml, has a BigDecimal field with @XmlValue, which becomes the element's text, and a String field with @XmlAttribute named currency, plus a no-argument constructor. Then MoneyAdapter extends XmlAdapter of AmountXml and Money: unmarshal looks up the Currency, sets the scale to the currency's fraction digits and builds the record; marshal does the reverse.

On the field I put @XmlJavaTypeAdapter of MoneyAdapter. The adapter is also where I make precision explicit: BigDecimal only, never double; 12.5 becomes 12.50, but 12.505 throws rather than rounding silently unless the contract defines a rounding mode; and I write plain numbers, never scientific notation.

I would test the adapter directly and with round trips through real XML for normal, zero, negative, zero-decimal currencies like yen, and invalid currencies, and set a validation event handler so adapter errors fail the message instead of producing null.

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 "Your XML contract represents money as <amount currency="EUR">12.50</amount>, but your...": https://scrivio-interview-library.netlify.app/java/jaxb/8b9f1f90d1/