1/* 2 * Copyright (C) 2007 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.google.common.base; 18 19import java.util.Collections; 20import java.util.HashMap; 21import java.util.Map; 22 23/** 24 * This class provides default values for all Java types, as defined by the JLS. 25 * 26 * @author Ben Yu 27 */ 28public final class Defaults { 29 private Defaults() {} 30 31 private static final Map<Class<?>, Object> DEFAULTS; 32 33 static { 34 Map<Class<?>, Object> map = new HashMap<Class<?>, Object>(); 35 put(map, boolean.class, false); 36 put(map, char.class, '\0'); 37 put(map, byte.class, (byte) 0); 38 put(map, short.class, (short) 0); 39 put(map, int.class, 0); 40 put(map, long.class, 0L); 41 put(map, float.class, 0f); 42 put(map, double.class, 0d); 43 DEFAULTS = Collections.unmodifiableMap(map); 44 } 45 46 private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) { 47 map.put(type, value); 48 } 49 50 /** 51 * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code 52 * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and 53 * {@code void}, null is returned. 54 */ 55 @SuppressWarnings("unchecked") 56 public static <T> T defaultValue(Class<T> type) { 57 return (T) DEFAULTS.get(type); 58 } 59} 60