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