@XmlSee也是另类 [英] @XmlSeeAlso alternative

查看:105
本文介绍了@XmlSee也是另类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

class A{
    @XmlElement
    String name;

    //getters and setters
}

class B extends A{
    @XmlElement
    String height;

    //getters and setters
}

最后我有

@XmlRootElement
class P{
    @XmlElement
    List<A> things;

    //getters and setters
}

如果我这样做

List<A> l = new ArrayList<A>();
l.add(new B('hello', 20)) //Add new B with height of 20 and name hello

P p = new P();
p.setThings(l); //Set things to list of B's.

和编组P,我只将该字段作为事物的一部分而非高度。

and marshal P, I only get the field as part of things and not height.

我知道我可以在A中添加@XmlSeeAlso(B.class)并且它都可以工作。

I know that I can add @XmlSeeAlso(B.class) in A and it will all work.

但问题是是因为我不知道B以外的所有扩展类,因为A可以在运行时扩展。

But the issue is that I don't know all extended classes other than B, as A may be extended on runtime.

如何在运行时动态定义@XmlSeeAlso?

How do I dynamically define @XmlSeeAlso on runtime?

推荐答案

这取决于你如何创建 JAXBContext newInstance方法,该方法的文档也给出了类似的示例。

This depends on how you are creating your JAXBContext. The newInstance method can be called with an explicit list of all your classes, the documentation for that method also gives a similar example.


客户端应用程序必须提供新上下文对象需要识别的类列表。不仅新的上下文将识别所有指定的类,而且它还将识别从指定的类静态直接/间接引用的任何类。引用类的子类和@XmlTransient引用的类未在JAXBContext中注册。例如,在下面的Java代码中,如果你执行newInstance(Foo.class),新创建的JAXBContext将识别Foo和Bar,但不识别Zot或FooBar:

The client application must supply a list of classes that the new context object needs to recognize. Not only the new context will recognize all the classes specified, but it will also recognize any classes that are directly/indirectly referenced statically from the specified classes. Subclasses of referenced classes nor @XmlTransient referenced classes are not registered with JAXBContext. For example, in the following Java code, if you do newInstance(Foo.class), the newly created JAXBContext will recognize both Foo and Bar, but not Zot or FooBar:



class Foo {
    @XmlTransient FooBar c;
    Bar b;
}
class Bar { int x; }
class Zot extends Bar { int y; }
class FooBar { }

编辑:如果你知道的话至少你可以使用的潜在jaxb类的包名称根据上下文路径创建上下文

If you know at least the package names of potential jaxb classes you could also create a context given a context path.

如果上述情况不可能,您还可以根据要序列化的对象,在运行时创建类列表。我认为最好尝试重构代码以使其不必要。以下代码未经测试:

If the above is not possible you could also create the list of classes at runtime, based on the object you want to serialize. I think it would be better to try to refactor your code to make this unnecessary. The code below is untested:

Set<Class> classes = new HashSet<Class>();
classes.add(p.getClass());
for (A a : p.getThings()) {
    classes.add(a.getClass());
}
JAXBContext context = JAXBContext.newInstance(classes.toArray(new Class[classes.size()]));

这篇关于@XmlSee也是另类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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