public class FormatFacade { public static byte[] formatJavaBean(String formatID, Object javaBean) throws FormatterException { ReadAdapter adapter = new JavaReadAdapter(javaBean); FormatElement format = FormatFactory.getFormatElement(formatID); Message message = format.format(adapter); return message.toBytes(); } public static void unformatJavaBean(String formatID, byte[] data, Object javaBean) throws FormatterException { WriteAdapter adapter = new JavaWriteAdapter(javaBean); FormatElement format = FormatFactory.getFormatElement(formatID); format.unformat(new Message(data), adapter); } }
You can call method public static FormatElement FormatFactory.getFormatElement(String formatID) to get the instance of format element for the formatID defined in the xml file. FormatFactory caches the format element instance of each formatID for further usage.
<format.xml> <format id="PersonFormat"> <record> <fString dataName="name" encoding="cp937"/> <selfLength/> <fInteger dataName="age" byteOrdering="host"/> <selfLength/> </record> </format> </format.xml>
FormatElement format = FormatFactory.getFormatElement(formatID);
FormatDefine format = new FormatDefine(); format.setId("PersonFormat"); RecordFormat record = new RecordFormat(); StringFormat strF = new StringFormat(); strF.setDataName("name"); strF.setEncoding("cp937"); SelfLength selfLength1 = new SelfLength(); IntegerFormat intF = new IntegerFormat(); intF.setDataName("age"); intF.setByteOrdering("host"); SelfLength selfLength2 = new SelfLength(); record.addChild(strF); record.addChild(selfLength1); record.addChild(intF); record.addChild(selfLength2); format.addChild(record);