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