Java Object Serialize and Deserialize serializeDeserialize(T obj)

Here you can find the source of serializeDeserialize(T obj)

Description

Tests if something is serializable.

License

Apache License

Parameter

Parameter Description
obj the item to serialize and deserialize

Return

whatever's left after serializing and deserializing the original item. Sometimes things throw exceptions.

Declaration


@SuppressWarnings("unchecked")
public static <T> T serializeDeserialize(T obj) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
    /**/*www  .j  a  va 2 s  .  c o  m*/
     Tests if something is serializable.
     Note: Lambdas and anonymous classes are NOT serializable in Java 8.  Only enums and classes that implement
     Serializable are.  This might be the best reason to use enums for singletons.
     @param obj the item to serialize and deserialize
     @return whatever's left after serializing and deserializing the original item.  Sometimes things throw exceptions.
     */

    @SuppressWarnings("unchecked")
    public static <T> T serializeDeserialize(T obj) {

        // This method was started by sblommers.  Thanks for your help!
        // Mistakes are Glen's.
        // https://github.com/GlenKPeterson/Paguro/issues/10#issuecomment-242332099

        // Write
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);

            final byte[] data = baos.toByteArray();

            // Read
            ByteArrayInputStream baip = new ByteArrayInputStream(data);
            ObjectInputStream ois = new ObjectInputStream(baip);
            return (T) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. serializeAndRecover(Object o)
  2. serializeAndReturnDeserializedObject( T object)
  3. serializeAndUnserialize(T t)
  4. serializeDeserialize(final Serializable object)
  5. serializeDeserialize(Object object)
  6. serializeThenDeserialize(T object)