1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.commons.io.input; 18 19 import java.io.IOException; 20 import java.io.InputStream; 21 import java.io.ObjectInputStream; 22 import java.io.ObjectStreamClass; 23 import java.io.StreamCorruptedException; 24 25 /** 26 * A special ObjectInputStream that loads a class based on a specified 27 * <code>ClassLoader</code> rather than the system default. 28 * <p> 29 * This is useful in dynamic container environments. 30 * 31 * @author Paul Hammant 32 * @version $Id: ClassLoaderObjectInputStream.java 437567 2006-08-28 06:39:07Z bayard $ 33 * @since Commons IO 1.1 34 */ 35 public class ClassLoaderObjectInputStream extends ObjectInputStream { 36 37 /** The class loader to use. */ 38 private ClassLoader classLoader; 39 40 /** 41 * Constructs a new ClassLoaderObjectInputStream. 42 * 43 * @param classLoader the ClassLoader from which classes should be loaded 44 * @param inputStream the InputStream to work on 45 * @throws IOException in case of an I/O error 46 * @throws StreamCorruptedException if the stream is corrupted 47 */ 48 public ClassLoaderObjectInputStream( 49 ClassLoader classLoader, InputStream inputStream) 50 throws IOException, StreamCorruptedException { 51 super(inputStream); 52 this.classLoader = classLoader; 53 } 54 55 /** 56 * Resolve a class specified by the descriptor using the 57 * specified ClassLoader or the super ClassLoader. 58 * 59 * @param objectStreamClass descriptor of the class 60 * @return the Class object described by the ObjectStreamClass 61 * @throws IOException in case of an I/O error 62 * @throws ClassNotFoundException if the Class cannot be found 63 */ 64 protected Class resolveClass(ObjectStreamClass objectStreamClass) 65 throws IOException, ClassNotFoundException { 66 67 Class clazz = Class.forName(objectStreamClass.getName(), false, classLoader); 68 69 if (clazz != null) { 70 // the classloader knows of the class 71 return clazz; 72 } else { 73 // classloader knows not of class, let the super classloader do it 74 return super.resolveClass(objectStreamClass); 75 } 76 } 77 } 78