代码之家  ›  专栏  ›  技术社区  ›  Mac

爪哇:jaxb Generircs

  •  1
  • Mac  · 技术社区  · 16 年前

    如何让JAXB绑定到我的向量?我似乎不能让它绑定包含泛型的向量,因为它抱怨它不能识别我的类“shape”或它的任何子类型。[javax.xml.bind.jaxbexception:类shape.shape或其任何超级类在此上下文中都是已知的。]“?

    import java.util.Vector;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    @XmlAccessorType(XmlAccessType.NONE)
    @XmlRootElement(name = "XVector")
    public class XVector<shape> {
    
        private Vector<shape> q;
    
        public XVector() {}
    
        @XmlElement(name = "q")
        public Vector<shape> getVector() {
            return q;
        }
    
        public void setVector(Vector<shape> q) {
            this.q = q;
        }
    }
    

    我得到以下错误:

    javax.xml.bind.MarshalException
     - with linked exception:
    [javax.xml.bind.JAXBException: class shape.Rectangle nor any of its super class is known to this context.]
            at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:317)
            at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:243)
            at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:75)
    

    public void saveFile(File filename) {
        try {
            FileOutputStream fout = new FileOutputStream(filename);
            objs.setVector(objVec);
            JAXBContext context = JAXBContext.newInstance(XVector.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    
            marshaller.marshal(objs, fout);
            fout.close();
        } catch (JAXBException e) {
           e.printStackTrace ();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    1 回复  |  直到 16 年前
        1
  •  2
  •   Bozho    16 年前

    您应该在 JAXBContext

    JAXBContext context = JAXBContext.newInstance(XVector.class, shape.class);
    

    (注:公约规定 Shape 应大写)