Marshalling JAXB Elements with Less Amount of Code
Marshalling java objects which must be conveniently annotated according to JAXB 2.X specification, has become simpler than before. An entity has XmlRootElement annotation can be marshalled with JAXB as follows:
TruckType truck = new TruckType(); truck.setBrand("BMC"); truck.setModel("PRO 940 (8x2)"); // create an instance of JAXBContext for TruckType class JAXBContext context = JAXBContext.newInstance(TruckType.class); // create marshaller for JAXB context Marshaller m = context.createMarshaller(); // OPTIONAL: just for presentation m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // finally marshalling instance of TruckType to System.out m.marshal(truck, System.out);Another case for marshalling with JAXB is JAXBElement<T> classes where T is any class has valid annotations. Sample code demonstrates how to marshal JAXBElements:
CarType carType = new CarType(); carType.setBrand("BMW"); carType.setModel("3.20D"); ObjectFactory factory = new ObjectFactory(); JAXBElement<CarType> bmw = factory.createBMW(carType); JAXBContext context = JAXBContext.newInstance(bmw.getDeclaredType()); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(bmw, System.out);It's wise to use a utility class that wraps the marshal methods of Marshal class. In order to get rid of implementation of creating an instance of JAXBContext, Marshaller class and invoking its same methods, everytime. It will be also helpful to those programmers focusing on learning JAXB annotations.
@SuppressWarnings("unchecked") public static void marshall(Object o) { try { JAXBContext context; if (o instanceof JAXBElement) { JAXBElement jaxbElement = (JAXBElement) o; context = JAXBContext.newInstance(jaxbElement.getDeclaredType()); } else { context = JAXBContext.newInstance(o.getClass()); } Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(o, System.out); } catch (Exception e) { e.printStackTrace(); } }
Comments
Post a Comment
Thx for reading! Comments are appreciated...