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 Map<Class<?>, Object> map = new HashMap<Class<?>, Object>(); 038 put(map, boolean.class, false); 039 put(map, char.class, '\0'); 040 put(map, byte.class, (byte) 0); 041 put(map, short.class, (short) 0); 042 put(map, int.class, 0); 043 put(map, long.class, 0L); 044 put(map, float.class, 0f); 045 put(map, double.class, 0d); 046 DEFAULTS = Collections.unmodifiableMap(map); 047 } 048 049 private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) { 050 map.put(type, value); 051 } 052 053 /** 054 * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code 055 * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and 056 * {@code void}, null is returned. 057 */ 058 @SuppressWarnings("unchecked") 059 public static <T> T defaultValue(Class<T> type) { 060 return (T) DEFAULTS.get(checkNotNull(type)); 061 } 062}