001/* 002 * Copyright 2002-2020 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.core.serializer; 018 019import java.io.ByteArrayOutputStream; 020import java.io.IOException; 021import java.io.OutputStream; 022 023/** 024 * A strategy interface for streaming an object to an OutputStream. 025 * 026 * @author Gary Russell 027 * @author Mark Fisher 028 * @author Juergen Hoeller 029 * @since 3.0.5 030 * @param <T> the object type 031 * @see Deserializer 032 */ 033@FunctionalInterface 034public interface Serializer<T> { 035 036 /** 037 * Write an object of type T to the given OutputStream. 038 * <p>Note: Implementations should not close the given OutputStream 039 * (or any decorators of that OutputStream) but rather leave this up 040 * to the caller. 041 * @param object the object to serialize 042 * @param outputStream the output stream 043 * @throws IOException in case of errors writing to the stream 044 */ 045 void serialize(T object, OutputStream outputStream) throws IOException; 046 047 /** 048 * Turn an object of type T into a serialized byte array. 049 * @param object the object to serialize 050 * @return the resulting byte array 051 * @throws IOException in case of serialization failure 052 * @since 5.2.7 053 */ 054 default byte[] serializeToByteArray(T object) throws IOException { 055 ByteArrayOutputStream out = new ByteArrayOutputStream(1024); 056 serialize(object, out); 057 return out.toByteArray(); 058 } 059 060}