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     */
028    public final class Defaults {
029      private Defaults() {}
030    
031      private static final Map<Class<?>, Object> DEFAULTS;
032    
033      static {
034        Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
035        put(map, boolean.class, false);
036        put(map, char.class, '\0');
037        put(map, byte.class, (byte) 0);
038        put(map, short.class, (short) 0);
039        put(map, int.class, 0);
040        put(map, long.class, 0L);
041        put(map, float.class, 0f);
042        put(map, double.class, 0d);
043        DEFAULTS = Collections.unmodifiableMap(map);
044      }
045    
046      private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) {
047        map.put(type, value);
048      }
049    
050      /**
051       * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code
052       * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and
053       * {@code void}, null is returned.
054       */
055      @SuppressWarnings("unchecked")
056      public static <T> T defaultValue(Class<T> type) {
057        return (T) DEFAULTS.get(type);
058      }
059    }