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
017package com.google.common.base;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.Map;
024
025/**
026 * This class provides default values for all Java types, as defined by the JLS.
027 *
028 * @author Ben Yu
029 * @since 1.0
030 */
031public final class Defaults {
032  private Defaults() {}
033
034  private static final Map<Class<?>, Object> DEFAULTS;
035
036  static {
037    // Only add to this map via put(Map, Class<T>, T)
038    Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
039    put(map, boolean.class, false);
040    put(map, char.class, '\0');
041    put(map, byte.class, (byte) 0);
042    put(map, short.class, (short) 0);
043    put(map, int.class, 0);
044    put(map, long.class, 0L);
045    put(map, float.class, 0f);
046    put(map, double.class, 0d);
047    DEFAULTS = Collections.unmodifiableMap(map);
048  }
049
050  private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) {
051    map.put(type, value);
052  }
053
054  /**
055   * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code
056   * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and
057   * {@code void}, null is returned.
058   */
059  public static <T> T defaultValue(Class<T> type) {
060    // Primitives.wrap(type).cast(...) would avoid the warning, but we can't use that from here
061    @SuppressWarnings("unchecked") // the put method enforces this key-value relationship
062    T t = (T) DEFAULTS.get(checkNotNull(type));
063    return t;
064  }
065}