Example usage for java.beans PersistenceDelegate PersistenceDelegate

List of usage examples for java.beans PersistenceDelegate PersistenceDelegate

Introduction

In this page you can find the example usage for java.beans PersistenceDelegate PersistenceDelegate.

Prototype

PersistenceDelegate

Source Link

Usage

From source file:com.swingtech.commons.util.ClassUtil.java

/**
 * NOTE: When using this to print an object it will not display the
 * primitive type boolean. Must use the wrapper class. All other primitives
 * work fine.//from  w  ww.  ja  v a2 s  .c  o m
 *
 * NOTE: If an int value has a 0 it won't display.
 *
 * NOTE: Object must have a public constructor.
 *
 * @param object
 * @return
 */
public static String getXMLForObject(final Object object) {
    ByteArrayOutputStream baos = null;
    XMLEncoder e = null;

    baos = new ByteArrayOutputStream();
    e = new XMLEncoder(new BufferedOutputStream(baos));

    e.setPersistenceDelegate(Date.class, new PersistenceDelegate() {
        @Override
        protected Expression instantiate(final Object oldInstance, final Encoder out) {
            final Date date = (Date) oldInstance;
            final Long time = new Long(date.getTime());
            return new Expression(date, date.getClass(), "new", new Object[] { time });
        }
    });

    e.setPersistenceDelegate(BigDecimal.class, new PersistenceDelegate() {
        @Override
        protected Expression instantiate(final Object oldInstance, final Encoder out) {
            final BigDecimal bigDec = (BigDecimal) oldInstance;
            final double doubleVal = bigDec.doubleValue();
            return new Expression(bigDec, bigDec.getClass(), "new", new Object[] { new Double(doubleVal) });
        }
    });

    e.writeObject(object);
    e.close();

    return baos.toString();
}