JAXB编组声明父类与实际运行时子类 [英] JAXB marshalling declared parent class vs. actual runtime subclass

查看:100
本文介绍了JAXB编组声明父类与实际运行时子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JAXB编组一个具有声明为类Foo的实例变量的类。在运行时,实例变量被设置为Foo的子类的实例,让我们说FooBar。类Foo和FooBar上都有基本的JAXB注释。

I'm using JAXB to marshal a class that has an instance variable that's declared as class Foo. At runtime that instance variable is set to an instance of a subclass of Foo, let's say FooBar. There are basic JAXB annotations on both class Foo and FooBar.

XML输出显示正在封送Foo的实例而不是FooBar。是否有一些特定的东西我需要做注释告诉JAXB如何正确编组运行时子类来代替声明的超类?

The XML output shows that an instance of Foo is being marshaled instead of FooBar. Is there something specific I have to do in terms of annotations to tell JAXB how to properly marshal the runtime subclass in lieu of the declared superclass?

我试过一个实验,其中我直接编组了一个Foo类型的实例变量foo,它在运行时被设置为FooBar的一个实例。它正确编组了一个FooBar实例。

I tried an experiment in which I directly marshaled an instance variable foo of type Foo that was set to an instance of FooBar at runtime. It correctly marshaled an instance of FooBar.

这明显不同于编组包含Foo类型的实例变量的类,因为marshal调用是在包含的类上进行的,而JAXB只是编组那些类字段(I使用@XmlAccessorType(XmlAccessType.FIELD)注释。)

This is clearly different from marshaling a class that contains an instance variable of type Foo because the marshal call is made on the containing class and JAXB just marshals that classes fields (I'm using the @XmlAccessorType(XmlAccessType.FIELD) annotation).

我的期望是JAXB可以正确检查实例变量的运行时类型,但可能不是这样。这种情况是否要求使用此处所述的XmlAdapter实现?

My expectation was that JAXB could properly inspect the runtime type of the instance variable but perhaps that's not the case. Does this situation call for using an implementation of XmlAdapter as described here?

JAXB继承,unmarshal到marshaled类的子类

谢谢,

Chris

推荐答案

我将以这些类为例:

@XmlRootElement
class Foo { public Bar bar; }
class Bar {}
class Baz extends Bar {}
class Quux extends Bar {}

好吧,似乎有两种可能的解决方案:

Well, there seem to be two possible solutions:

您可以在创建上下文时告诉JAXB所有涉及的类(包括子类)。

You can tell JAXB about all involved classes (including subclasses) at context creation time.

JAXBContext.newInstance(Foo.class, Bar.class, Baz.class, Quux.class);

通过 @XmlSeeAlso 注释。

@XmlRootElement
@XmlSeeAlso({Baz.class, Quux.class})
class Foo { public Bar bar; }

如果你像这样编组

Foo f = new Foo();
f.bar = new Baz();

m.marshal(f, System.err);

您收到

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <bar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="baz"/>
</foo>

它不漂亮但保留了类型信息。

It's not beautiful but type information is preserved.

这篇关于JAXB编组声明父类与实际运行时子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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