Jason Alati
Jason Alati

Reputation: 245

Java: Generic JAXB Serialization

I'm looking for a generic way to serialize objects in Java using JAXB XML Serialization. I'd like to have something like this:

public static <T> String serializeUsingJAXB(T entity) {
    JAXBContext context = JAXBContext.newInstance(T.class);
    // ...
}

However, it looks as though due to type erasure, T.class doesn't work.

What will?

Upvotes: 2

Views: 7080

Answers (4)

bdoughan
bdoughan

Reputation: 149047

You might also consider:

public static <T> String serializeUsingJAXB(T entity) { 
    StringWriter writer = new StringWriter();
    javax.xml.bind.JAXB.marshal(entity, writer);
    return writer.toString();
} 

For more information see the javax.xml.bind.JAXB class

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

The obvious answer is:

public static String serializeUsingJAXB(Object entity, JAXBContext context) {
    // ...
}

Upvotes: 0

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45596

public static <T> String serializeUsingJAXB(
    T entity,
    Class< ? extends T> clazz
)
{
    JAXBContext context = JAXBContext.newInstance( clazz );
    // ...
}

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328770

Try entity.getClass()

Upvotes: 6

Related Questions