Here you can find the source of deserializeAndCheckObject(final byte[] object, final Class extends Serializable> type)
Parameter | Description |
---|---|
T | the type parameter |
object | the object |
type | the type |
public static <T> T deserializeAndCheckObject(final byte[] object, final Class<? extends Serializable> type)
//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); } } } } }