Fatcatfats
Fatcatfats

Reputation: 53

How to create a JAXB Marshaller that takes a Generic object

Essentially what I'm trying to do is create a marshaller that can take any class object I give it for example a car object or a person object and it must return a XML string.

Here is what I've got so far:

 public <T> String CreateXML(T objToSerialize)
    {
        String xml = "";
        try 
        {           

        JAXBContext context = JAXBContext.newInstance(objToSerialize.getClass());
        Marshaller marshaler = context.createMarshaller(); 
        StringWriter writer = new StringWriter();
        marshaler.marshal(objToSerialize.getClass(),writer);
        xml = writer.toString();
            System.out.println(xml);
            return xml;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return xml;
    }

It gives me the following error:

WARNING: An illegal reflective access operation has occurred

Upvotes: 1

Views: 4606

Answers (2)

Rene Stadler
Rene Stadler

Reputation: 66

In your code, you marshal the class of the objectToSerialize and not the object itself. You can either change this line

marshaler.marshal(objToSerialize.getClass(), writer);
//to
marshaler.marshal(objToSerialize, writer);

or try this code instead:

public static <T> String marshall(T data) {
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(data.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        StringWriter stringWriter = new StringWriter();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(data, stringWriter);
        return stringWriter.toString();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return null;
}

Upvotes: 5

Andrei Maimas
Andrei Maimas

Reputation: 695

For a generic conversion try this:

StringWriter sw = new StringWriter();
JAXBContext.newInstance(((JAXBElement) argument).getDeclaredType()).createMarshaller().marshal(argument, sw);
sb.append(sw.toString());

Upvotes: 0

Related Questions