Java Object Serialize and Deserialize deserializeAndCheckObject(final byte[] object, final Class type)

Here you can find the source of deserializeAndCheckObject(final byte[] object, final Class type)

Description

Decode and serialize object.

License

Apache License

Parameter

Parameter Description
T the type parameter
object the object
type the type

Return

the t

Declaration

public static <T> T deserializeAndCheckObject(final byte[] object, final Class<? extends Serializable> type) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import java.io.Serializable;

public class Main {
    /**//from   w  w w  .j a v  a2 s  .co m
     * Decode and serialize object.
     *
     * @param <T>  the type parameter
     * @param object the object
     * @param type the type
     * @return the t
     * @since 4.2
     */
    public static <T> T deserializeAndCheckObject(final byte[] object, final Class<? extends Serializable> type) {
        final Object result = deserialize(object);
        if (!type.isAssignableFrom(result.getClass())) {
            throw new ClassCastException(
                    "Decoded object is of type " + result.getClass() + " when we were expecting " + type);
        }
        return (T) result;
    }

    /**
     * Deserialize an object.
     * @param <T>  the type parameter
     * @param inBytes The bytes to be deserialized
     * @return the object
     * @since 5.0.0
     */
    public static <T> T deserialize(final byte[] inBytes) {
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(inBytes);
        return deserialize(inputStream);
    }

    /**
     * Deserialize an object.
     * @param <T>  the type parameter
     * @param inputStream The stream to be deserialized
     * @return the object
     * @since 5.0.0
     */
    public static <T> T deserialize(final InputStream inputStream) {
        ObjectInputStream in = null;
        try {
            in = new ObjectInputStream(inputStream);
            final T obj = (T) in.readObject();
            return obj;
        } catch (final ClassNotFoundException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (final IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

Related

  1. deserialize(String name)
  2. deserialize(String serialized)
  3. deserialize(String serializedObject)
  4. deserialize(String str)
  5. deSerialize(String str)
  6. deserialized(final byte[] data)
  7. deserializeFromString(String obj)
  8. deserializeGZip(byte[] buf, T obj)
  9. deserializeJdk(byte[] bytes)