001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.base; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.GwtIncompatible; 020import com.google.common.annotations.J2ktIncompatible; 021import org.jspecify.annotations.Nullable; 022 023/** 024 * This class provides default values for all Java types, as defined by the JLS. 025 * 026 * @author Ben Yu 027 * @since 1.0 028 */ 029@J2ktIncompatible 030@GwtIncompatible 031public final class Defaults { 032 private Defaults() {} 033 034 private static final Double DOUBLE_DEFAULT = 0d; 035 private static final Float FLOAT_DEFAULT = 0f; 036 037 /** 038 * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code 039 * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and 040 * {@code void}, {@code null} is returned. 041 */ 042 @SuppressWarnings({ 043 /* 044 * `type.cast(...)` would be wrong because `type` is a primitive. We'd need 045 * `c.g.c.primitives.Primitives.wrap(type).cast(...)`, and we can't depend on `primitives` from 046 * `base`. 047 */ 048 "unchecked", 049 "BooleanLiteral" // `(T) false` would produce an error 050 }) 051 public static <T> @Nullable T defaultValue(Class<T> type) { 052 checkNotNull(type); 053 if (type.isPrimitive()) { 054 if (type == boolean.class) { 055 return (T) Boolean.FALSE; 056 } else if (type == char.class) { 057 return (T) Character.valueOf('\0'); 058 } else if (type == byte.class) { 059 return (T) Byte.valueOf((byte) 0); 060 } else if (type == short.class) { 061 return (T) Short.valueOf((short) 0); 062 } else if (type == int.class) { 063 return (T) Integer.valueOf(0); 064 } else if (type == long.class) { 065 return (T) Long.valueOf(0L); 066 } else if (type == float.class) { 067 return (T) FLOAT_DEFAULT; 068 } else if (type == double.class) { 069 return (T) DOUBLE_DEFAULT; 070 } 071 } 072 return null; 073 } 074}