使用Guava的Optional与@XmlAttribute [英] Using Guava's Optional with @XmlAttribute

查看:384
本文介绍了使用Guava的Optional与@XmlAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个带JAXB注释的Java类,以下列格式生成一些XML:

I would like to setup a JAXB-annotated Java class to generate some XML in the following format:

<page refId="0001">
    <title>The title of my page</title>
</page>

refId字段是可选的,所以我想使用Guava的Optional构造来引用内存中的字符串。我看到使用通用@XmlJavaTypeAdapter解压缩包装在Guava的Optional中,如果你正在使用一个元素,它会提供一个完整的例子(即使这不是原始问题),但是你如何设置XML属性的注释?

The "refId" field is optional, so I'd like to use Guava's Optional construct to reference the string in memory. I see Using generic @XmlJavaTypeAdapter to unmarshal wrapped in Guava's Optional, which gives a thorough example if you're using an element (even if that wasn't the original question), but how would you set up the annotations for an XML attribute?

这是我到目前为止所拥有的:

Here's what I have so far:

@XmlRootElement(name="page")
public final class Page {
    @XmlAttribute
    @XmlJavaTypeAdapter(OptionalAdapter.class)
    private Optional<String> refId;

    @XmlElement
    private String title;

    ... getters/setters, default constructor, etc.
}

而OptionalAdapter是一个简单的XmlAdapter:

And OptionalAdapter is a simple XmlAdapter:

public class OptionalAdapter<T> extends XmlAdapter<T, Optional<T>> {

    @Override
    public Optional<T> unmarshal(T v) throws Exception {
        return Optional.fromNullable(v);
    }

    @Override
    public T marshal(Optional<T> v) throws Exception {
        if (v == null || !v.isPresent()) {
            return null;
        } else {
            return v.get();
        }
    }
}

当我尝试加载时针对上述代码的单元测试,它在初始化期间立即失败,但是如果我将注释更改为@XmlElement,测试将运行并通过,但显然将refId设置为子元素而不是属性。

When I try to load up a unit test against the above code, it fails instantly during initialization, but if I change the annotation to @XmlElement, the test will run and pass, but obviously sets the refId as a child element instead of an attribute.

提前致谢!

推荐答案

Xml-attribute只能有简单类型(如字符串整数等),因此您不能使用 OptionalAdapter< T>

如果您的字段的类型为 String ,那么适配器的类型应为 OptionalAdapter< String>

您可以通过以下方式进行操作:

- 创建其他类,并使用 XmlAdapter

Xml-attribute can have only simple type (like String, Integer etc.), so you cann't use OptionalAdapter<T>.
If your field has type String then adapter should have type OptionalAdapter<String>.
You can do in next way:
- create additional class, and use is as XmlAdapter

   public final class StringOptionalAdapter extends OptionalAdapter<String>
   {
   }  

Page.java

   @XmlAttribute
   @XmlJavaTypeAdapter(StringOptionalAdapter.class)
   private Optional<String> refId;

这篇关于使用Guava的Optional与@XmlAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆