001    /*
002     * Copyright (C) 2007 Google Inc.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005     * in compliance with the License. You may obtain a copy of the License at
006     *
007     * http://www.apache.org/licenses/LICENSE-2.0
008     *
009     * Unless required by applicable law or agreed to in writing, software distributed under the License
010     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011     * or implied. See the License for the specific language governing permissions and limitations under
012     * the License.
013     */
014    
015    package com.google.common.base;
016    
017    import java.util.HashMap;
018    import java.util.Map;
019    
020    /**
021     * This class provides default values for all Java types, as defined by the JLS.
022     *
023     * @author Ben Yu
024     */
025    public final class Defaults {
026      private Defaults() {}
027    
028      private static final Map<Class<?>, Object> DEFAULTS = new HashMap<Class<?>, Object>(16);
029    
030      private static <T> void put(Class<T> type, T value) {
031        DEFAULTS.put(type, value);
032      }
033    
034      static {
035        put(boolean.class, false);
036        put(char.class, '\0');
037        put(byte.class, (byte) 0);
038        put(short.class, (short) 0);
039        put(int.class, 0);
040        put(long.class, 0L);
041        put(float.class, 0f);
042        put(double.class, 0d);
043      }
044    
045      /**
046       * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code
047       * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and
048       * {@code void}, null is returned.
049       */
050      @SuppressWarnings("unchecked")
051      public static <T> T defaultValue(Class<T> type) {
052        return (T) DEFAULTS.get(type);
053      }
054    }