@XmlSeeAlso 替代 [英] @XmlSeeAlso alternative

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

问题描述

我有以下几点:

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

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

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