Radoslav
Radoslav

Reputation: 85

How to use generics in argument need class

In my example JAXBContext.newInstance(T) need paramether Class and this solution with generics not works.

public class SerializationUtilJaxb<T> {

    public String serialize(T jaxbObject) {
        StringWriter stringWriter = new StringWriter();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(T);
            Marshaller objectMarshaller = jaxbContext.createMarshaller();
            objectMarshaller.marshal(jaxbObject, stringWriter);
            return stringWriter.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
}

Can I ask why? And what is correct solution with generics?

Upvotes: 0

Views: 37

Answers (1)

ulab
ulab

Reputation: 1089

Use unbounded wildcard ? instead.

public static void SerializationUtilJaxb(Class<?> rootClass, Object rootObj) throws JAXBException, IOException{

        try{
            StringWriter stringWriter = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(rootClass);
            Marshaller m = context.createMarshaller();      
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            m.marshal(rootObj, stringwriter);
        }
        catch(Exception e){
            // System.out.println (e.getMessage);
            throw e;
        }
    }

Upvotes: 1

Related Questions