Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

java - Using Guava's Optional with @XmlAttribute

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>

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.
}

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();
        }
    }
}

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.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...