1 /* 2 * Copyright (C) 2007 Google Inc. 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 17 package com.google.common.base; 18 19 import java.util.HashMap; 20 import java.util.Map; 21 22 /** 23 * This class provides default values for all Java types, as defined by the JLS. 24 * 25 * @author Ben Yu 26 */ 27 public final class Defaults { 28 private Defaults() {} 29 30 private static final Map<Class<?>, Object> DEFAULTS = 31 new HashMap<Class<?>, Object>(16); 32 33 private static <T> void put(Class<T> type, T value) { 34 DEFAULTS.put(type, value); 35 } 36 37 static { 38 put(boolean.class, false); 39 put(char.class, '\0'); 40 put(byte.class, (byte) 0); 41 put(short.class, (short) 0); 42 put(int.class, 0); 43 put(long.class, 0L); 44 put(float.class, 0f); 45 put(double.class, 0d); 46 } 47 48 /** 49 * Returns the default value of {@code type} as defined by JLS --- {@code 0} 50 * for numbers, {@code false} for {@code boolean} and {@code '\0'} for {@code 51 * char}. For non-primitive types and {@code void}, null is returned. 52 */ 53 @SuppressWarnings("unchecked") 54 public static <T> T defaultValue(Class<T> type) { 55 return (T) DEFAULTS.get(type); 56 } 57 } 58