简体   繁体   中英

JAXBContext.newInstance with generic class as input

I have several JavaBeans like this (getter and setter omitted):

@Entity
@XmlRootElement(name = "talent")
public class Talent extends BaseObject implements Serializable {

    String gruppe;
    String art;
}

and xml-files for them, all like

<body>
    <item>
        <gruppe>a</gruppe>
        <art>b</art>
    </item>
    <item>
        <gruppe>a</gruppe>
        <art>b</art>
    </item>
</body> 

now i want to read these xml files into my object. for the list I wrote a generic wrapper class as follows:

@XmlRootElement(name = "body")
public class GenericWrapper<E extends BaseObject> {

    private ArrayList<E> talentListe;

    public ArrayList<E> getTalentListe() {
        return talentListe;
    }

    @XmlElement(name = "item")
    public void setTalentListe(ArrayList<E> talentListo) {
        this.talentListe = talentListo;
    }
}

the problem occurs when i want to instantiate the JAXBContext:

JAXBContext context = JAXBContext.newInstance(GenericWrapper.class);
Unmarshaller um = context.createUnmarshaller();
GenericWrapper<Talent> gw = (GenericWrapper<Talent>) um.unmarshal(new FileReader(STORE_FILENAME));
List<Elementar> list = gw.getTalentListe();

then the errormessage occurs:

Exception in thread "main" javax.xml.bind.UnmarshalException: Unable to create an instance of struktur.BaseObject

if I don't make my wrapperclass generic, everything works fine. I guess the problem is, when i want to get the JAXBContext.newInstance from my generic wrapper class, the generic part is not set, so it tries to use the most basic constructor from BaseObject which is abstract... how do I tell the method to generate the wrapper.class as a instance of GenericWrapper? that he uses the constructor of Talent, rather than my abstract BaseObject.

PS: I'm sure i forgot a lot of needed information. plz coment, and i will provide everything needed. If a hole other aproach seems more reasonable, I'm willing to listen as well. but in general an answer to this question would be nice.

EDIT: BaseObject is just an MappedSuperclass and struktur the package:

@MappedSuperclass
@PrimaryKeyJoinColumn(name = "colConfig")
public abstract class BaseObject {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    int id;
    private String name;
    @Column(columnDefinition = "TEXT")
    private String beschreibung;

We don't know what BaseObject or struktur are ... https://stackoverflow.com/help/mcve

Having said that, as per JAXB and abstract classes , you could try annotating just the impl classes to be @XmlRootElement and the abstract class to be @XmlTransient

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM