Search code examples
javajaxb

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


Solution

  • 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;
    }