Java Object Serialize serialize(@Nullable Object value)

Here you can find the source of serialize(@Nullable Object value)

Description

Turns an object into a byte array.

License

Open Source License

Return

serialized object or null if value is null

Declaration

@Nullable
public static byte[] serialize(@Nullable Object value) 

Method Source Code

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.io.ObjectOutputStream;
import javax.annotation.Nullable;

public class Main {
    /**//w  ww .j ava 2  s .  c om
     * Turns an object into a byte array.
     *
     * @return serialized object or {@code null} if {@code value} is {@code null}
     */
    @Nullable
    public static byte[] serialize(@Nullable Object value) {
        if (value == null) {
            return null;
        }
        ByteArrayOutputStream objectBytes = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(objectBytes)) {
            oos.writeObject(value);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to serialize: " + value, e);
        }
        return objectBytes.toByteArray();
    }
}

Related

  1. serialize(@Nonnull T object)
  2. serialize(@Nullable final Object obj)
  3. serialize(File outFile, Object source)
  4. serialize(final @Nonnull Object obj)
  5. serialize(final File file, final Object o)
  6. serialize(final Object object)