001/* 002 * Copyright 2002-2015 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.IOException; 020import java.io.InputStream; 021import java.io.ObjectInputStream; 022 023import org.springframework.core.ConfigurableObjectInputStream; 024import org.springframework.core.NestedIOException; 025 026/** 027 * A default {@link Deserializer} implementation that reads an input stream 028 * using Java serialization. 029 * 030 * @author Gary Russell 031 * @author Mark Fisher 032 * @author Juergen Hoeller 033 * @since 3.0.5 034 * @see ObjectInputStream 035 */ 036public class DefaultDeserializer implements Deserializer<Object> { 037 038 private final ClassLoader classLoader; 039 040 041 /** 042 * Create a {@code DefaultDeserializer} with default {@link ObjectInputStream} 043 * configuration, using the "latest user-defined ClassLoader". 044 */ 045 public DefaultDeserializer() { 046 this.classLoader = null; 047 } 048 049 /** 050 * Create a {@code DefaultDeserializer} for using an {@link ObjectInputStream} 051 * with the given {@code ClassLoader}. 052 * @since 4.2.1 053 * @see ConfigurableObjectInputStream#ConfigurableObjectInputStream(InputStream, ClassLoader) 054 */ 055 public DefaultDeserializer(ClassLoader classLoader) { 056 this.classLoader = classLoader; 057 } 058 059 060 /** 061 * Read from the supplied {@code InputStream} and deserialize the contents 062 * into an object. 063 * @see ObjectInputStream#readObject() 064 */ 065 @Override 066 @SuppressWarnings("resource") 067 public Object deserialize(InputStream inputStream) throws IOException { 068 ObjectInputStream objectInputStream = new ConfigurableObjectInputStream(inputStream, this.classLoader); 069 try { 070 return objectInputStream.readObject(); 071 } 072 catch (ClassNotFoundException ex) { 073 throw new NestedIOException("Failed to deserialize object type", ex); 074 } 075 } 076 077}