---
title: "Using JAXB 2.0's XmlJavaTypeAdapter"
author: "卡拉阿风"
date: "2010-12-22T09:30:50Z"
tags: []
categories: ["企业架构"]
slug: "using-jaxb-2-0-s-xmljavatypeadapter"
draft: false
lastmod: "2010-12-22T09:31:33Z"
id: 848895
url: "https://alimama.iteye.com/blog/848895"
---

有时，有的类和xml无法完全绑定，即xml和类中的某个属性无法绑定；同时JAXB要求类必须有个默认的构造函数，否则会出现如下错误

```
error: java.sql.Timestamp does not have a no-arg default constructor

```

注：这里用java.sql.Timestamp 表示无法和xml绑定的类

 

这个时候我们要写一个继承自`XmlAdapter的adapter类，如下：`

```
import java.sql.Timestamp;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class TimestampAdapter extends XmlAdapter<Date, Timestamp> {

   public Date marshal(Timestamp t) {
     return new Date(t.getTime());
   }

   public Timestamp unmarshal(Date d) {
     return new Timestamp (d.getTime());
   }

}
```

 然后使用@XmlJavaTypeAdapter标记到使用java.sql.Timestamp类的地方，例如：

```
@XmlRootElement
public class InfoDTO {
  private Timestamp createTime;
  ...
  @XmlJavaTypeAdapter(Timestamp.class)
  public Timestamp getCreateTime() {
    return this.createTime;
  }

}
```

 

更多请参考： [http://weblogs.java.net/blog/2005/09/30/using-jaxb-20s-xmljavatypeadapter](http://weblogs.java.net/blog/2005/09/30/using-jaxb-20s-xmljavatypeadapter)