Reputation: 245
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
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
Reputation: 147164
The obvious answer is:
public static String serializeUsingJAXB(Object entity, JAXBContext context) {
// ...
}
Upvotes: 0
Reputation: 45596
public static <T> String serializeUsingJAXB(
T entity,
Class< ? extends T> clazz
)
{
JAXBContext context = JAXBContext.newInstance( clazz );
// ...
}
Upvotes: 1