Java Object Serialize and Deserialize serializeAndDeserialize(T object)

Here you can find the source of serializeAndDeserialize(T object)

Description

serialize And Deserialize

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    public static <T extends Serializable> T serializeAndDeserialize(T object) throws Exception 

Method Source Code


//package com.java2s;
/*//from   w  w  w .  j  a  v a  2 s. co  m
 * Copyright 2015-2017 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v2.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v20.html
 */

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

public class Main {
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T serializeAndDeserialize(T object) throws Exception {
        byte[] bytes = serialize(object);
        return (T) deserialize(bytes);
    }

    private static byte[] serialize(Object object) throws Exception {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        }
    }

    private static Object deserialize(byte[] bytes) throws Exception {
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
            return in.readObject();
        }
    }
}

Related

  1. serializeAndDeserialize(Object obj)
  2. serializeAndDeserialize(T input)
  3. serializeAndDeserialize(T instance)
  4. serializeAndDeserialize(T obj)
  5. serializeAndDeserialize(T object)
  6. serializeAndDeserialize(T object)
  7. serializeAndDeserializeObject(Object myObject)
  8. serializeAndGetObject(Object obj)
  9. serializeAndReadObject(File envHome, Object object)