This class provides default values for all Java types, as defined by the JLS. @author Ben Yu @since 1.0
| 30 | |
| 31 | |
| 32 | @GwtIncompatible |
| 33 | public final class Defaults { |
| 34 | private Defaults() {} |
| 35 | |
| 36 | private static final Map<Class<?>, Object> DEFAULTS; |
| 37 | |
| 38 | static { |
| 39 | // Only add to this map via put(Map, Class<T>, T) |
| 40 | Map<Class<?>, Object> map = new HashMap<Class<?>, Object>(); |
| 41 | put(map, boolean.class, false); |
| 42 | put(map, char.class, '\0'); |
| 43 | put(map, byte.class, (byte) 0); |
| 44 | put(map, short.class, (short) 0); |
| 45 | put(map, int.class, 0); |
| 46 | put(map, long.class, 0L); |
| 47 | put(map, float.class, 0f); |
| 48 | put(map, double.class, 0d); |
| 49 | DEFAULTS = Collections.unmodifiableMap(map); |
| 50 | } |
| 51 | |
| 52 | |
| 53 | private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) { |
| 54 | map.put(type, value); |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code |
| 59 | * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and |
| 60 | * {@code void}, {@code null} is returned. |
| 61 | */ |
| 62 | |
| 63 | @Nullable |
| 64 | public static <T> T defaultValue(Class<T> type) { |
| 65 | // Primitives.wrap(type).cast(...) would avoid the warning, but we can't use that from here |
| 66 | @SuppressWarnings("unchecked") // the put method enforces this key-value relationship |
| 67 | T t = (T) DEFAULTS.get(checkNotNull(type)); |
| 68 | return t; |
| 69 | } |
| 70 | } |
nothing calls this directly
no test coverage detected