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