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.Map; 026 import java.util.concurrent.ConcurrentHashMap; 027 028 /** Factories for non-public writables. Defining a factory permits {@link 029 * ObjectWritable} to be able to construct instances of non-public classes. */ 030 @InterfaceAudience.Public 031 @InterfaceStability.Stable 032 public class WritableFactories { 033 private static final Map<Class, WritableFactory> CLASS_TO_FACTORY = 034 new ConcurrentHashMap<Class, WritableFactory>(); 035 036 private WritableFactories() {} // singleton 037 038 /** Define a factory for a class. */ 039 public static void setFactory(Class c, WritableFactory factory) { 040 CLASS_TO_FACTORY.put(c, factory); 041 } 042 043 /** Define a factory for a class. */ 044 public static WritableFactory getFactory(Class c) { 045 return CLASS_TO_FACTORY.get(c); 046 } 047 048 /** Create a new instance of a class with a defined factory. */ 049 public static Writable newInstance(Class<? extends Writable> c, Configuration conf) { 050 WritableFactory factory = WritableFactories.getFactory(c); 051 if (factory != null) { 052 Writable result = factory.newInstance(); 053 if (result instanceof Configurable) { 054 ((Configurable) result).setConf(conf); 055 } 056 return result; 057 } else { 058 return ReflectionUtils.newInstance(c, conf); 059 } 060 } 061 062 /** Create a new instance of a class with a defined factory. */ 063 public static Writable newInstance(Class<? extends Writable> c) { 064 return newInstance(c, null); 065 } 066 067 } 068