views:

60

answers:

4

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?

+3  A: 

Try entity.getClass()

Aaron Digulla
sneaky stuff :)
willcodejavaforfood
My goodness, that was easy. Thanks!
Jason Alati
@Jason: Make sure that in your requirements `entity` is never `null`. If it ever is, you'll get NPE.
Alexander Pogrebnyak
Yes, I will certainly do that. Thanks.
Jason Alati
You could also use the JAXB class and save a line or two of code see, http://stackoverflow.com/questions/3549334/java-generic-jaxb-serialization/3549916#3549916
Blaise Doughan
+1  A: 
public static <T> String serializeUsingJAXB(
    T entity,
    Class< ? extends T> clazz
)
{
    JAXBContext context = JAXBContext.newInstance( clazz );
    // ...
}
Alexander Pogrebnyak
`T` could be `Object` there...
Tom Hawtin - tackline
@Tom. It could, but I have no clue what's the rest of this method looks like. This is pretty generic Generics programming technique.
Alexander Pogrebnyak
@Alexander It doesn't matter what the rest of the method is.
Tom Hawtin - tackline
A: 

The obvious answer is:

public static String serializeUsingJAXB(Object entity, JAXBContext context) {
    // ...
}
Tom Hawtin - tackline
A: 

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:

Blaise Doughan
Thanks for that, it's good to know. I don't mind doing it the long way since I can set the JAXB_FORMATTED_OUTPUT property of the Marshaller to false.
Jason Alati