Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.beans.XMLDecoder;

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import org.xml.sax.SAXParseException;

public class Main {
    /***
     * Deserialize a xml string into an object
     * 
     * @param <T>
     *            type of the object to deserialize to
     * @param xmlString
     *            xml string represents an object
     * @param classToCastTo
     *            class to deserialize to
     * @return object deserialized from the xml
     * @throws SAXParseException
     *             if xmlString is not well formatted
     * @throws ClassCastException
     *             if the object is not the an instance of classToCastTo
     */
    public static <T> T deserializeObject(final String xmlString, final Class<T> classToCastTo)
            throws SAXParseException, ClassCastException {

        final InputStream fis = new ByteArrayInputStream(xmlString.getBytes());

        return deserializeObject(fis, classToCastTo);

    }

    /***
     * Deserialize a xml string into an object
     * 
     * @param <T>
     *            type of the object to deserialize to
     * @param xmlStream
     *            xml stream represents an object
     * @param classToCastTo
     *            class to deserialize to
     * @return object deserialized from the xml
     * @throws SAXParseException
     *             if xmlString is not well formatted
     * @throws ClassCastException
     *             if the object is not the an instance of classToCastTo
     */
    @SuppressWarnings("unchecked")
    public static <T> T deserializeObject(final InputStream xmlStream, final Class<T> classToCastTo)
            throws SAXParseException, ClassCastException {

        // Create XML decoder.
        final XMLDecoder xmlDecoder = new XMLDecoder(xmlStream);

        try {

            final Object deserializedObj = xmlDecoder.readObject();

            // Will not perform cast check,
            // Let the casting throw ClassCastException if needed.
            return (T) deserializedObj;
        } finally {
            if (xmlDecoder != null) {
                xmlDecoder.close();
            }
        }

    }
}