本文介绍了将 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?

这是我目前所拥有的:

@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 只能有简单类型(如 StringInteger 等),所以你不能使用 OptionalAdapter.
如果您的字段具有 String 类型,则适配器应具有 OptionalAdapter 类型.
您可以通过以下方式进行:
- 创建额外的类,使用为 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 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 01:07