001    /*
002     * Copyright (C) 2007 The Guava 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     * http://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    
017    package com.google.common.base;
018    
019    import java.util.Collections;
020    import java.util.HashMap;
021    import java.util.Map;
022    
023    /**
024     * This class provides default values for all Java types, as defined by the JLS.
025     *
026     * @author Ben Yu
027     * @since 1.0
028     */
029    public final class Defaults {
030      private Defaults() {}
031    
032      private static final Map<Class<?>, Object> DEFAULTS;
033    
034      static {
035        Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
036        put(map, boolean.class, false);
037        put(map, char.class, '\0');
038        put(map, byte.class, (byte) 0);
039        put(map, short.class, (short) 0);
040        put(map, int.class, 0);
041        put(map, long.class, 0L);
042        put(map, float.class, 0f);
043        put(map, double.class, 0d);
044        DEFAULTS = Collections.unmodifiableMap(map);
045      }
046    
047      private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) {
048        map.put(type, value);
049      }
050    
051      /**
052       * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code
053       * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and
054       * {@code void}, null is returned.
055       */
056      @SuppressWarnings("unchecked")
057      public static <T> T defaultValue(Class<T> type) {
058        return (T) DEFAULTS.get(type);
059      }
060    }