-
Book Overview & Buying
-
Table Of Contents
Java Coding Problems - Second Edition
By :
Serializing/deserializing objects to XML via the JDK API can be accomplished via java.beans.XMLEncoder, respectively XMLDecoder. The XMLEncoder API relies on Java Reflection to discover the object’s fields and write them in XML format. This class can encode objects that respect the Java Beans contract (https://docs.oracle.com/javase/tutorial/javabeans/writing/index.html). Basically, the object’s class should contain a public no-arguments constructor and public getters and setters for private/protected fields/properties. Implementing Serializable is not mandatory for XMLEncoder/XMLDecoder, so we can serialize/deserialize objects that don’t implement Serializable. Here, it is a helper method that encodes the given Object to XML:
public static String objectToXML(Object obj)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try ( XMLEncoder encoder = new XMLEncoder(
...