com.migesok.jaxb.adapter.javatime.TemporalAccessorXmlAdapter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jaxb-java-time-adapters Show documentation
Show all versions of jaxb-java-time-adapters Show documentation
JAXB adapters for Java 8 Date and Time API (JSR-310) types
The newest version!
package com.migesok.jaxb.adapter.javatime;
import javax.annotation.Nonnull;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
import static java.util.Objects.requireNonNull;
/**
* {@code XmlAdapter} mapping any JSR-310 {@code TemporalAccessor} to string using provided {@code DateTimeFormatter}
*
* Example:
*
* {@code
* public class DottedDateXmlAdapter extends TemporalAccessorXmlAdapter {
* public DottedDateXmlAdapter() {
* super(DateTimeFormatter.ofPattern("dd.MM.yyyy"), LocalDate::from);
* }
* }
* }
*
*
* @param mapped temporal type
* @see javax.xml.bind.annotation.adapters.XmlAdapter
* @see java.time.temporal.TemporalAccessor
* @see java.time.format.DateTimeFormatter
*/
public class TemporalAccessorXmlAdapter extends XmlAdapter {
private final DateTimeFormatter formatter;
private final TemporalQuery extends T> temporalQuery;
/**
* @param formatter the formatter for printing and parsing, not null
* @param temporalQuery the query defining the type to parse to, not null
*/
public TemporalAccessorXmlAdapter(@Nonnull DateTimeFormatter formatter,
@Nonnull TemporalQuery extends T> temporalQuery) {
this.formatter = requireNonNull(formatter, "formatter must not be null");
this.temporalQuery = requireNonNull(temporalQuery, "temporal query must not be null");
}
@Override
public T unmarshal(String stringValue) {
return stringValue != null ? formatter.parse(stringValue, temporalQuery) : null;
}
@Override
public String marshal(T value) {
return value != null ? formatter.format(value) : null;
}
}