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