Here you can find the source of serialize(Object obj)
Parameter | Description |
---|---|
obj | the object to serialize |
Parameter | Description |
---|---|
IOException | if the serialization fails |
public static byte[] serialize(Object obj) throws IOException
//package com.java2s; /*//from w w w . j a va2 s .com * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class Main { /** * Serializes an object into a byte array. When the object is null, returns null. * * @param obj the object to serialize * @return the serialized bytes * @throws IOException if the serialization fails */ public static byte[] serialize(Object obj) throws IOException { if (obj == null) { return null; } try (ByteArrayOutputStream b = new ByteArrayOutputStream()) { try (ObjectOutputStream o = new ObjectOutputStream(b)) { o.writeObject(obj); } return b.toByteArray(); } } /** * Wrapper around {@link #serialize(Object)} which throws a runtime exception with the given * message on failure. * * @param obj the object the serialize * @param errorMessage the message to show if serialization fails * @return the serialized bytes */ public static byte[] serialize(Object obj, String errorMessage) { try { return serialize(obj); } catch (IOException e) { throw new RuntimeException(errorMessage, e); } } }