blob: beed751708d050cf4a5a4ae6956f3989269a4f0c [file] [log] [blame]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>Using an XmlAdapter | EclipseLink 2.7 EclipseLink MOXy</title>
<meta name="generator" content="Oracle DARB XHTML Converter (Mode = document) - Version 1.0.22 Build 1" />
<meta name="date" content="2014-06-10T10:25:32Z" />
<meta name="robots" content="noarchive" />
<meta name="doctitle" content="Using an XmlAdapter" />
<meta name="relnum" content="Release 2.7" />
<meta name="partnum" content="" />
<link rel="stylesheet" type="text/css" href="../../dcommon/style.css" media="screen" />
<link rel="copyright" href="../../dcommon/html/cpyr.htm" title="Copyright" type="text/html" />
<link rel="start" href="../../index.htm" title="Home" type="text/html" />
<link rel="contents" href="toc.htm" title="Contents" type="text/html" />
<link rel="prev" href="advanced_concepts005.htm" title="Previous" type="text/html" />
<link rel="next" href="advanced_concepts007.htm" title="Next" type="text/html" />
<!-- START: Disqus --><script type="text/javascript"> var disqus_developer = 0; </script><!-- END: Disqus --><!-- START: Sharethis --><script type="text/javascript">var switchTo5x=true;</script><script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script><script type="text/javascript" src="http://s.sharethis.com/loader.js"></script> <!-- END: Sharethis --></head>
<body bgcolor="#FFFFFF"><iframe id="docheader" frameborder="0" framemargin="0" scrolling="no" src="../../dcommon/header.html"></iframe><script src="http://www.google.com/jsapi" type="text/javascript"></script><script type="text/javascript"> google.load('search', '1', {language : 'en'}); google.setOnLoadCallback(function() { var customSearchOptions = {}; var googleAnalyticsOptions = {}; googleAnalyticsOptions['queryParameter'] = 'q'; googleAnalyticsOptions['categoryParameter'] = ''; customSearchOptions['googleAnalyticsOptions'] = googleAnalyticsOptions; var customSearchControl = new google.search.CustomSearchControl( '016171230611334810008:1hjujor5_fg', customSearchOptions); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.setSearchFormRoot('cse-search-form'); customSearchControl.draw('cse', options); }, true);</script><link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" /><div id="cse" style="width:100%;"></div>
<div class="header"><a id="top" name="top"></a>
<table class="simple oac_no_warn" summary="" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td align="left" valign="top"><div class="booktitle">Developing JAXB Applications Using EclipseLink MOXy,
<b>Release 2.7</b><br /></font></td>
<td valign="bottom" align="right" width="144">
<table class="simple oac_no_warn" summary="" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td>&nbsp;</td>
<td align="center" valign="top"><a href="toc.htm"><img src="../../dcommon/images/contents.png" alt="Go To Table Of Contents" border="0" height="16" width="16" /><br />
</td><td>&nbsp;</td><td align="center"><a href="../../" target="_top" class="external text" title="Search" rel="nofollow"><img src="../../dcommon/images/search.png" alt="Search" style="border:0;" /><br /><span class="mini"></span></a></td><td>&nbsp;</td><td align="center"><a href="../eclipselink_moxy.pdf" title="PDF" target="_blank"><img src="../../dcommon/images/pdf_icon.png" style="padding-right:5px;border:0" alt="PDF"></a></td>
</tr>
</table>
</td>
</tr>
</table>
<hr />
<table class="navigation simple oac_no_warn" summary="" cellspacing="0" cellpadding="0" width="100" align="center">
<tr>
<td align="center"><a href="advanced_concepts005.htm"><img src="../../dcommon/images/larrow.png" alt="Previous" border="0" height="16" width="16" /></a></td>
<td align="center"><a href="advanced_concepts007.htm"><img src="../../dcommon/images/rarrow.png" alt="Next" border="0" height="16" width="16" /></a></td>
<td>&nbsp;</td>
</tr>
</table>
</div>
<!-- class="header" -->
<div class="ind"><!-- End Header --><a id="CHDCEDIG" name="CHDCEDIG"></a><a id="TLJAX418" name="TLJAX418"></a>
<div class="sect1"><!-- infolevel="all" infotype="General" -->
<h1 class="sect1"><font face="arial, helvetica, sans-serif" color="#330099">Using an XmlAdapter</font></h1>
<p>Some Java classes may not be well suited for use with JAXB and at first glance may seem "unmappable" &ndash; for example, classes that do not have a default <code>no-arg</code> constructor, or classes for which an XML representation cannot be automatically determined. Using JAXB's <code>XmlAdapter</code>, you can define custom code to convert the unmappable class into something that JAXB can handle. Then, you can use the <code>@XmlJavaTypeAdapter</code> annotation to indicate that your adapter should be used when working with the unmappable class.</p>
<p><code>XmlAdapter</code> uses the following terminology:</p>
<ul>
<li>
<p><code>ValueType</code> &ndash; The type that JAXB knows how to handle out of the box.</p>
</li>
<li>
<p><code>BoundType</code> &ndash; The type that JAXB doesn't know how to handle. An adapter is written to allow this type to be used as an in-memory representation through the ValueType.</p>
</li>
</ul>
<p>The outline of an XmlAdapter class is as follows:</p>
<div class="example"><a id="TLJAX419" name="TLJAX419"></a><a id="sthref178" name="sthref178"></a>
<p><strong><em><font face="arial, helvetica, sans-serif">Example 8-32 XmlAdapter Class Outline</font></em></strong></p>
<pre xml:space="preserve" class="oac_no_warn">
public class AdapterName extends XmlAdapter&lt;ValueType, BoundType&gt; {
public BoundType unmarshal(ValueType value) throws Exception {
...
}
public ValueType marshal(BoundType value) throws Exception {
...
}
}
</pre></div>
<!-- class="example" -->
<a id="TLJAX420" name="TLJAX420"></a>
<div class="sect2"><a id="sthref179" name="sthref179"></a>
<h2 class="sect2"><font face="arial, helvetica, sans-serif" color="#330099">Using java.util.Currency</font></h2>
<p>Our first example will use the following domain class:</p>
<div class="example"><a id="TLJAX421" name="TLJAX421"></a><a id="sthref180" name="sthref180"></a>
<p><strong><em><font face="arial, helvetica, sans-serif">Example 8-33 Sample Domain Class</font></em></strong></p>
<pre xml:space="preserve" class="oac_no_warn">
package example;
import java.util.Currency;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class PurchaseOrder {
private Double amount;
private Currency currency;
...
}
</pre></div>
<!-- class="example" -->
<p>Here, the <strong>Currency</strong> cannot be automatically mapped with JAXB because it does not contain a no-argument constructor. However, we can write an adapter that will convert the <strong>Currency</strong> into something that JAXB does know how to handle &ndash; a simple <code>String</code>. Luckily, in this case the <strong>Currency's</strong> <code>toString()</code> method returns the currency code, which can also be used to create a new <strong>Currency</strong>:</p>
<div class="example"><a id="TLJAX422" name="TLJAX422"></a><a id="sthref181" name="sthref181"></a>
<p><strong><em><font face="arial, helvetica, sans-serif">Example 8-34 Using an Adapter</font></em></strong></p>
<pre xml:space="preserve" class="oac_no_warn">
package example;
import java.util.Currency;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class CurrencyAdapter extends XmlAdapter&lt;String, Currency&gt; {
/*
* Java =&gt; XML
* Given the unmappable Java object, return the desired XML representation.
*/
public String marshal(Currency val) throws Exception {
return val.toString();
}
/*
* XML =&gt; Java
* Given an XML string, use it to build an instance of the unmappable class.
*/
public Currency unmarshal(String val) throws Exception {
return Currency.getInstance(val);
}
}
</pre></div>
<!-- class="example" -->
<p>To indicate that our adapter should be used for the <strong>Currency</strong> property, we annotate it with <code>@XmlJavaTypeAdapter</code> and provide the class name of our adapter:</p>
<div class="example"><a id="TLJAX423" name="TLJAX423"></a><a id="sthref182" name="sthref182"></a>
<p><strong><em><font face="arial, helvetica, sans-serif">Example 8-35 Using the @XmlJavaTypeAdapter Annotation</font></em></strong></p>
<pre xml:space="preserve" class="oac_no_warn">
package example;
import java.util.Currency;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class PurchaseOrder {
private Double amount;
<strong>@XmlJavaTypeAdapter</strong>(CurrencyAdapter.class)
private Currency currency;
...
}
</pre></div>
<!-- class="example" --></div>
<!-- class="sect2" -->
<a id="TLJAX424" name="TLJAX424"></a>
<div class="sect2"><a id="sthref183" name="sthref183"></a>
<h2 class="sect2"><font face="arial, helvetica, sans-serif" color="#330099">Using java.awt.Point</font></h2>
<p>Sometimes the best way to handle an unmappable class is to write a "stand-in" class which <em>can</em> be mapped with JAXB, and convert between the two classes in the <code>XmlAdapter</code>. In this example, we want to use the <strong>Point</strong> class. Because of that class' <code>getLocation()</code> method (which JAXB will pickup automatically and map), an infinite loop will occur during marshalling. Because we cannot change the <strong>Point</strong> class, we will write a new class, <strong>MyPoint</strong>, and use it in the adapter.</p>
<div class="example"><a id="TLJAX425" name="TLJAX425"></a><a id="sthref184" name="sthref184"></a>
<p><strong><em><font face="arial, helvetica, sans-serif">Example 8-36 Using java.awt.Point</font></em></strong></p>
<pre xml:space="preserve" class="oac_no_warn">
package example;
public class MyPoint {
private int x, y;
public MyPoint() {
this(0, 0);
}
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
...
}
package example;
import java.awt.Point;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class MyPointAdapter extends XmlAdapter&lt;MyPoint, Point&gt; {
/*
* Java =&gt; XML
*/
public MyPoint marshal(Point val) throws Exception {
return new MyPoint((int) val.getX(), (int) val.getY());
}
/*
* XML =&gt; Java
*/
public Point unmarshal(MyPoint val) throws Exception {
return new Point(val.getX(), val.getY());
}
}
</pre></div>
<!-- class="example" -->
<p>Finally, our <strong>Point</strong> properties are marked with <code>@XmlJavaTypeAdapter</code>:</p>
<div class="example"><a id="CHDBBDAC" name="CHDBBDAC"></a><a id="TLJAX426" name="TLJAX426"></a>
<p><strong><em><font face="arial, helvetica, sans-serif">Example 8-37 Using the @XmlJavaTypeAdapter Annotation</font></em></strong></p>
<pre xml:space="preserve" class="oac_no_warn">
package example;
import java.awt.Point;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Zone {
private String name;
<strong>@XmlJavaTypeAdapter</strong>(MyPointAdapter.class)
private Point startCoord;
<strong>@XmlJavaTypeAdapter</strong>(MyPointAdapter.class)
private Point endCoord;
...
}
</pre></div>
<!-- class="example" --></div>
<!-- class="sect2" -->
<a id="TLJAX427" name="TLJAX427"></a>
<div class="sect2"><a id="sthref185" name="sthref185"></a>
<h2 class="sect2"><font face="arial, helvetica, sans-serif" color="#330099">Specifying Package-Level Adapters</font></h2>
<p>In <a href="#CHDBBDAC">Example 8-37</a>, we annotated both <strong>Point</strong> properties with the <code>@XmlJavaTypeAdapter</code> annotation. If you have many of these types of properties &ndash; for example, in other domain classes &ndash; it can be more convenient to specify the <strong>@XmlJavaTypeAdapters</strong> at the package level.</p>
<p>We could define both of the adapter classes in <strong>package-info.java</strong>, and would no longer have to annotate any further <strong>Currency</strong> or <strong>Point</strong> properties:</p>
<pre xml:space="preserve" class="oac_no_warn">
@XmlJavaTypeAdapters({
@XmlJavaTypeAdapter(value=CurrencyAdapter.class,type=Currency.class),
@XmlJavaTypeAdapter(value=MyPointAdapter.class,type=Point.class)
})
package example;
</pre></div>
<!-- class="sect2" -->
<a id="TLJAX428" name="TLJAX428"></a>
<div class="sect2"><a id="sthref186" name="sthref186"></a>
<h2 class="sect2"><font face="arial, helvetica, sans-serif" color="#330099">Specifying Class-Level @XmlJavaTypeAdapters</font></h2>
<p>If you have a Java class and you would like to always use an <code>XmlAdapter</code> during marshalling and unmarshalling, then you can specify the <code>@XmlJavaTypeAdapter</code> directly at the class level:</p>
<pre xml:space="preserve" class="oac_no_warn">
package example;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlJavaTypeAdapter(DataStructureAdapter.class)
public class DataStructure {
...
}
</pre>
<p>Now, any object that has a <strong>DataStructure</strong> property will automatically use the <code>DataStructureAdapter</code>, without the need for an annotation on the property itself.</p>
</div>
<!-- class="sect2" --></div>
<!-- class="sect1" --></div>
<!-- class="ind" -->
<!-- Start Footer -->
<div class="footer">
<hr />
<table class="simple oac_no_warn" summary="" cellspacing="0" cellpadding="0" width="100%">
<col width="33%" />
<col width="*" />
<col width="33%" />
<tr>
<td valign="bottom">
<table class="navigation simple oac_no_warn" summary="" cellspacing="0" cellpadding="0" width="100" align="center">
<col width="*" />
<col width="48%" />
<col width="48%" />
<tr>
<td>&nbsp;</td>
<td align="center"><a href="advanced_concepts005.htm"><img src="../../dcommon/images/larrow.png" alt="Previous" border="0" height="16" width="16" /></a></td>
<td align="center"><a href="advanced_concepts007.htm"><img src="../../dcommon/images/rarrow.png" alt="Next" border="0" height="16" width="16" /></a></td>
</tr>
</table>
</td>
<td align="center" width="34%"><a href="http://www.eclipse.org/eclipselink/" title="EclipseLink home"><img src="../../dcommon/images/ellogo.png" alt="EclipseLink" width="150" border="0" /></a><br />
<td valign="bottom" align="right">
<table class="simple oac_no_warn" summary="" cellspacing="0" cellpadding="0" width="225">
<tr>
<td>&nbsp;</td>
<td align="center" valign="top"><a href="toc.htm"><img src="../../dcommon/images/contents.png" alt="Go To Table Of Contents" border="0" height="16" width="16" /><br />
</td><td>&nbsp;</td><td align="center"><a href="../../" target="_top" class="external text" title="Search" rel="nofollow"><img src="../../dcommon/images/search.png" alt="Search" style="border:0;" /><br /><span class="mini"></span></a></td><td>&nbsp;</td><td align="center"><a href="../eclipselink_moxy.pdf" title="PDF" target="_blank"><img src="../../dcommon/images/pdf_icon.png" style="padding-right:5px;border:0" alt="PDF"></a></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<!-- class="footer" -->
<div id="copyright">Copyright &copy; 2013 by The Eclipse Foundation under the <a href="http://www.eclipse.org/org/documents/epl-v10.php">Eclipse Public License (EPL)</a><br /> <script type="text/javascript">var LastUpdated = document.lastModified;document.writeln ("Updated: " + LastUpdated);</script> </div><!-- START: Analytics --><script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1608008-2']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script><!-- END: Analytics --><!-- START: Sharethis --><script>var options={ "publisher": "e2fe9e07-fab6-4f84-83ea-0991b429842c", "position": "right", "ad": { "visible": false, "openDelay": 5, "closeDelay": 0}};var st_hover_widget = new sharethis.widgets.hoverbuttons(options);</script><!-- END: Sharethis --></body>
</html>