001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    
019    package org.apache.hadoop.io;
020    
021    import org.apache.hadoop.classification.InterfaceAudience;
022    import org.apache.hadoop.classification.InterfaceStability;
023    import org.apache.hadoop.conf.*;
024    import org.apache.hadoop.util.ReflectionUtils;
025    import java.util.HashMap;
026    
027    /** Factories for non-public writables.  Defining a factory permits {@link
028     * ObjectWritable} to be able to construct instances of non-public classes. */
029    @InterfaceAudience.Public
030    @InterfaceStability.Stable
031    public class WritableFactories {
032      private static final HashMap<Class, WritableFactory> CLASS_TO_FACTORY =
033        new HashMap<Class, WritableFactory>();
034    
035      private WritableFactories() {}                  // singleton
036    
037      /** Define a factory for a class. */
038      public static synchronized void setFactory(Class c, WritableFactory factory) {
039        CLASS_TO_FACTORY.put(c, factory);
040      }
041    
042      /** Define a factory for a class. */
043      public static synchronized WritableFactory getFactory(Class c) {
044        return CLASS_TO_FACTORY.get(c);
045      }
046    
047      /** Create a new instance of a class with a defined factory. */
048      public static Writable newInstance(Class<? extends Writable> c, Configuration conf) {
049        WritableFactory factory = WritableFactories.getFactory(c);
050        if (factory != null) {
051          Writable result = factory.newInstance();
052          if (result instanceof Configurable) {
053            ((Configurable) result).setConf(conf);
054          }
055          return result;
056        } else {
057          return ReflectionUtils.newInstance(c, conf);
058        }
059      }
060      
061      /** Create a new instance of a class with a defined factory. */
062      public static Writable newInstance(Class<? extends Writable> c) {
063        return newInstance(c, null);
064      }
065    
066    }
067