栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从JAXB泛型中删除xsi:type,xmlns:xs和xmlns:xsi

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从JAXB泛型中删除xsi:type,xmlns:xs和xmlns:xsi

通用测试

您的JAXB(JSR-222)实现将为每个类创建映射(即

TestGeneric
,不是type(即
TestGeneric<Integer>
)。因此,它将
value
字段视为type
Object
。这将导致
xsi:type
属性,因为JAXB实现正在添加足够的信息才能解组相同的类型。

@XmlAccessorType(XmlAccessType.NONE)static class TestGeneric<T> {    @XmlAttribute public boolean isRequired;    @XmlElement public T value;    public TestGeneric() {    }    public TestGeneric(boolean isRequired) {        this.isRequired = isRequired;    }}

演示版

下面是您可以使用的一种方法。我介绍了的子类

TestGeneric
来代表不同的可能类型。

package forum11192623;import java.io.PrintWriter;import java.io.StringWriter;import javax.xml.bind.*;import javax.xml.bind.annotation.*;public class Demo {    public static void main(String[] args) {        try { TestRoot root = new TestRoot(); root.name.value = "bobby"; root.age.value = 102; root.color.value = "blue"; JAXBContext context = JAXBContext.newInstance(root.getClass()); Marshaller marsh = context.createMarshaller(); marsh.setProperty(Marshaller.JAXB_ENCODING,"UTF-8"); marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); marsh.marshal(root,pw); System.out.println(sw.toString());        }        catch(Throwable t) { t.printStackTrace();        }    }    @XmlRootElement    static class TestRoot {        @XmlElement public TestString name = new TestString(true);        @XmlElement public TestInteger age = new TestInteger(true);        @XmlElement public TestString color = new TestString(true);    }    @XmlAccessorType(XmlAccessType.NONE)    @XmlTransient    @XmlSeeAlso({TestInteger.class, TestString.class})    static class TestGeneric<T> {        @XmlAttribute         public boolean isRequired;        public T value;        public TestGeneric() {        }        public TestGeneric(boolean isRequired) { this.isRequired = isRequired;        }    }    static class TestInteger extends TestGeneric<Integer> {        public TestInteger() {        }        public TestInteger(boolean b) { super(b);        }        @XmlElement        public Integer getValue() { return value;        }        public void setValue(Integer value) { this.value = value;        }    }    static class TestString extends TestGeneric<String> {        public TestString() {        }        public TestString(boolean b) { super(b);        }        @XmlElement        public String getValue() { return value;        }        public void setValue(String value) { this.value = value;        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464348.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号