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