• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.base;
16 
17 import static com.google.common.base.Preconditions.checkNotNull;
18 
19 import com.google.common.annotations.GwtIncompatible;
20 import javax.annotation.CheckForNull;
21 
22 /**
23  * This class provides default values for all Java types, as defined by the JLS.
24  *
25  * @author Ben Yu
26  * @since 1.0
27  */
28 @GwtIncompatible
29 @ElementTypesAreNonnullByDefault
30 public final class Defaults {
Defaults()31   private Defaults() {}
32 
33   private static final Double DOUBLE_DEFAULT = 0d;
34   private static final Float FLOAT_DEFAULT = 0f;
35 
36   /**
37    * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code
38    * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and
39    * {@code void}, {@code null} is returned.
40    */
41   @SuppressWarnings("unchecked")
42   @CheckForNull
defaultValue(Class<T> type)43   public static <T> T defaultValue(Class<T> type) {
44     checkNotNull(type);
45     if (type.isPrimitive()) {
46       if (type == boolean.class) {
47         return (T) Boolean.FALSE;
48       } else if (type == char.class) {
49         return (T) Character.valueOf('\0');
50       } else if (type == byte.class) {
51         return (T) Byte.valueOf((byte) 0);
52       } else if (type == short.class) {
53         return (T) Short.valueOf((short) 0);
54       } else if (type == int.class) {
55         return (T) Integer.valueOf(0);
56       } else if (type == long.class) {
57         return (T) Long.valueOf(0L);
58       } else if (type == float.class) {
59         return (T) FLOAT_DEFAULT;
60       } else if (type == double.class) {
61         return (T) DOUBLE_DEFAULT;
62       }
63     }
64     return null;
65   }
66 }
67