001/* 002 * Copyright (C) 2014 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.GwtCompatible; 020import com.google.errorprone.annotations.CanIgnoreReturnValue; 021import java.lang.reflect.Array; 022import java.util.Arrays; 023import java.util.Collection; 024import java.util.Map; 025import java.util.OptionalDouble; 026import java.util.OptionalInt; 027import java.util.OptionalLong; 028import javax.annotation.CheckForNull; 029 030/** 031 * Helper functions that operate on any {@code Object}, and are not already provided in {@link 032 * java.util.Objects}. 033 * 034 * <p>See the Guava User Guide on <a 035 * href="https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained">writing {@code Object} 036 * methods with {@code MoreObjects}</a>. 037 * 038 * @author Laurence Gonsalves 039 * @since 18.0 (since 2.0 as {@code Objects}) 040 */ 041@GwtCompatible 042@ElementTypesAreNonnullByDefault 043public final class MoreObjects { 044 /** 045 * Returns the first of two given parameters that is not {@code null}, if either is, or otherwise 046 * throws a {@link NullPointerException}. 047 * 048 * <p>To find the first non-null element in an iterable, use {@code Iterables.find(iterable, 049 * Predicates.notNull())}. For varargs, use {@code Iterables.find(Arrays.asList(a, b, c, ...), 050 * Predicates.notNull())}, static importing as necessary. 051 * 052 * <p><b>Note:</b> if {@code first} is represented as an {@link Optional}, this can be 053 * accomplished with {@link Optional#or(Object) first.or(second)}. That approach also allows for 054 * lazy evaluation of the fallback instance, using {@link Optional#or(Supplier) 055 * first.or(supplier)}. 056 * 057 * <p><b>Java 9 users:</b> use {@code java.util.Objects.requireNonNullElse(first, second)} 058 * instead. 059 * 060 * @return {@code first} if it is non-null; otherwise {@code second} if it is non-null 061 * @throws NullPointerException if both {@code first} and {@code second} are null 062 * @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}). 063 */ 064 /* 065 * We annotate firstNonNull in a way that protects against NullPointerException at the cost of 066 * forbidding some reasonable calls. 067 * 068 * The more permissive signature would be to accept (@CheckForNull T first, @CheckForNull T 069 * second), since it's OK for `second` to be null as long as `first` is not also null. But we 070 * expect for that flexibility to be useful relatively rarely: The more common use case is to 071 * supply a clearly non-null default, like `firstNonNull(someString, "")`. And users who really 072 * know that `first` is guaranteed non-null when `second` is null can write the logic out 073 * longhand, including a requireNonNull call, which calls attention to the fact that the static 074 * analyzer can't prove that the operation is safe. 075 * 076 * This matches the signature we currently have for requireNonNullElse in our own checker. (And 077 * that in turn matches that method's signature under the Checker Framework.) As always, we could 078 * consider the more flexible signature if we judge it worth the risks. If we do, we would likely 079 * update both methods so that they continue to match. 080 */ 081 public static <T> T firstNonNull(@CheckForNull T first, T second) { 082 if (first != null) { 083 return first; 084 } 085 if (second != null) { 086 return second; 087 } 088 throw new NullPointerException("Both parameters are null"); 089 } 090 091 /** 092 * Creates an instance of {@link ToStringHelper}. 093 * 094 * <p>This is helpful for implementing {@link Object#toString()}. Specification by example: 095 * 096 * <pre>{@code 097 * // Returns "ClassName{}" 098 * MoreObjects.toStringHelper(this) 099 * .toString(); 100 * 101 * // Returns "ClassName{x=1}" 102 * MoreObjects.toStringHelper(this) 103 * .add("x", 1) 104 * .toString(); 105 * 106 * // Returns "MyObject{x=1}" 107 * MoreObjects.toStringHelper("MyObject") 108 * .add("x", 1) 109 * .toString(); 110 * 111 * // Returns "ClassName{x=1, y=foo}" 112 * MoreObjects.toStringHelper(this) 113 * .add("x", 1) 114 * .add("y", "foo") 115 * .toString(); 116 * 117 * // Returns "ClassName{x=1}" 118 * MoreObjects.toStringHelper(this) 119 * .omitNullValues() 120 * .add("x", 1) 121 * .add("y", null) 122 * .toString(); 123 * }</pre> 124 * 125 * <p>Note that in GWT, class names are often obfuscated. 126 * 127 * @param self the object to generate the string for (typically {@code this}), used only for its 128 * class name 129 * @since 18.0 (since 2.0 as {@code Objects.toStringHelper()}). 130 */ 131 public static ToStringHelper toStringHelper(Object self) { 132 return new ToStringHelper(self.getClass().getSimpleName()); 133 } 134 135 /** 136 * Creates an instance of {@link ToStringHelper} in the same manner as {@link 137 * #toStringHelper(Object)}, but using the simple name of {@code clazz} instead of using an 138 * instance's {@link Object#getClass()}. 139 * 140 * <p>Note that in GWT, class names are often obfuscated. 141 * 142 * @param clazz the {@link Class} of the instance 143 * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}). 144 */ 145 public static ToStringHelper toStringHelper(Class<?> clazz) { 146 return new ToStringHelper(clazz.getSimpleName()); 147 } 148 149 /** 150 * Creates an instance of {@link ToStringHelper} in the same manner as {@link 151 * #toStringHelper(Object)}, but using {@code className} instead of using an instance's {@link 152 * Object#getClass()}. 153 * 154 * @param className the name of the instance type 155 * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}). 156 */ 157 public static ToStringHelper toStringHelper(String className) { 158 return new ToStringHelper(className); 159 } 160 161 /** 162 * Support class for {@link MoreObjects#toStringHelper}. 163 * 164 * @author Jason Lee 165 * @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}). 166 */ 167 public static final class ToStringHelper { 168 private final String className; 169 private final ValueHolder holderHead = new ValueHolder(); 170 private ValueHolder holderTail = holderHead; 171 private boolean omitNullValues = false; 172 private boolean omitEmptyValues = false; 173 174 /** Use {@link MoreObjects#toStringHelper(Object)} to create an instance. */ 175 private ToStringHelper(String className) { 176 this.className = checkNotNull(className); 177 } 178 179 /** 180 * Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with null 181 * value. The order of calling this method, relative to the {@code add()}/{@code addValue()} 182 * methods, is not significant. 183 * 184 * @since 18.0 (since 12.0 as {@code Objects.ToStringHelper.omitNullValues()}). 185 */ 186 @CanIgnoreReturnValue 187 public ToStringHelper omitNullValues() { 188 omitNullValues = true; 189 return this; 190 } 191 192 /** 193 * Adds a name/value pair to the formatted output in {@code name=value} format. If {@code value} 194 * is {@code null}, the string {@code "null"} is used, unless {@link #omitNullValues()} is 195 * called, in which case this name/value pair will not be added. 196 */ 197 @CanIgnoreReturnValue 198 public ToStringHelper add(String name, @CheckForNull Object value) { 199 return addHolder(name, value); 200 } 201 202 /** 203 * Adds a name/value pair to the formatted output in {@code name=value} format. 204 * 205 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}). 206 */ 207 @CanIgnoreReturnValue 208 public ToStringHelper add(String name, boolean value) { 209 return addUnconditionalHolder(name, String.valueOf(value)); 210 } 211 212 /** 213 * Adds a name/value pair to the formatted output in {@code name=value} format. 214 * 215 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}). 216 */ 217 @CanIgnoreReturnValue 218 public ToStringHelper add(String name, char value) { 219 return addUnconditionalHolder(name, String.valueOf(value)); 220 } 221 222 /** 223 * Adds a name/value pair to the formatted output in {@code name=value} format. 224 * 225 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}). 226 */ 227 @CanIgnoreReturnValue 228 public ToStringHelper add(String name, double value) { 229 return addUnconditionalHolder(name, String.valueOf(value)); 230 } 231 232 /** 233 * Adds a name/value pair to the formatted output in {@code name=value} format. 234 * 235 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}). 236 */ 237 @CanIgnoreReturnValue 238 public ToStringHelper add(String name, float value) { 239 return addUnconditionalHolder(name, String.valueOf(value)); 240 } 241 242 /** 243 * Adds a name/value pair to the formatted output in {@code name=value} format. 244 * 245 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}). 246 */ 247 @CanIgnoreReturnValue 248 public ToStringHelper add(String name, int value) { 249 return addUnconditionalHolder(name, String.valueOf(value)); 250 } 251 252 /** 253 * Adds a name/value pair to the formatted output in {@code name=value} format. 254 * 255 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}). 256 */ 257 @CanIgnoreReturnValue 258 public ToStringHelper add(String name, long value) { 259 return addUnconditionalHolder(name, String.valueOf(value)); 260 } 261 262 /** 263 * Adds an unnamed value to the formatted output. 264 * 265 * <p>It is strongly encouraged to use {@link #add(String, Object)} instead and give value a 266 * readable name. 267 */ 268 @CanIgnoreReturnValue 269 public ToStringHelper addValue(@CheckForNull Object value) { 270 return addHolder(value); 271 } 272 273 /** 274 * Adds an unnamed value to the formatted output. 275 * 276 * <p>It is strongly encouraged to use {@link #add(String, boolean)} instead and give value a 277 * readable name. 278 * 279 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}). 280 */ 281 @CanIgnoreReturnValue 282 public ToStringHelper addValue(boolean value) { 283 return addUnconditionalHolder(String.valueOf(value)); 284 } 285 286 /** 287 * Adds an unnamed value to the formatted output. 288 * 289 * <p>It is strongly encouraged to use {@link #add(String, char)} instead and give value a 290 * readable name. 291 * 292 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}). 293 */ 294 @CanIgnoreReturnValue 295 public ToStringHelper addValue(char value) { 296 return addUnconditionalHolder(String.valueOf(value)); 297 } 298 299 /** 300 * Adds an unnamed value to the formatted output. 301 * 302 * <p>It is strongly encouraged to use {@link #add(String, double)} instead and give value a 303 * readable name. 304 * 305 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}). 306 */ 307 @CanIgnoreReturnValue 308 public ToStringHelper addValue(double value) { 309 return addUnconditionalHolder(String.valueOf(value)); 310 } 311 312 /** 313 * Adds an unnamed value to the formatted output. 314 * 315 * <p>It is strongly encouraged to use {@link #add(String, float)} instead and give value a 316 * readable name. 317 * 318 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}). 319 */ 320 @CanIgnoreReturnValue 321 public ToStringHelper addValue(float value) { 322 return addUnconditionalHolder(String.valueOf(value)); 323 } 324 325 /** 326 * Adds an unnamed value to the formatted output. 327 * 328 * <p>It is strongly encouraged to use {@link #add(String, int)} instead and give value a 329 * readable name. 330 * 331 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}). 332 */ 333 @CanIgnoreReturnValue 334 public ToStringHelper addValue(int value) { 335 return addUnconditionalHolder(String.valueOf(value)); 336 } 337 338 /** 339 * Adds an unnamed value to the formatted output. 340 * 341 * <p>It is strongly encouraged to use {@link #add(String, long)} instead and give value a 342 * readable name. 343 * 344 * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}). 345 */ 346 @CanIgnoreReturnValue 347 public ToStringHelper addValue(long value) { 348 return addUnconditionalHolder(String.valueOf(value)); 349 } 350 351 private static boolean isEmpty(Object value) { 352 // Put types estimated to be most frequent first. 353 if (value instanceof CharSequence) { 354 return ((CharSequence) value).length() == 0; 355 } else if (value instanceof Collection) { 356 return ((Collection<?>) value).isEmpty(); 357 } else if (value instanceof Map) { 358 return ((Map<?, ?>) value).isEmpty(); 359 } else if (value instanceof java.util.Optional) { 360 return !((java.util.Optional<?>) value).isPresent(); 361 } else if (value instanceof OptionalInt) { 362 return !((OptionalInt) value).isPresent(); 363 } else if (value instanceof OptionalLong) { 364 return !((OptionalLong) value).isPresent(); 365 } else if (value instanceof OptionalDouble) { 366 return !((OptionalDouble) value).isPresent(); 367 } else if (value instanceof Optional) { 368 return !((Optional) value).isPresent(); 369 } else if (value.getClass().isArray()) { 370 return Array.getLength(value) == 0; 371 } 372 return false; 373 } 374 375 /** 376 * Returns a string in the format specified by {@link MoreObjects#toStringHelper(Object)}. 377 * 378 * <p>After calling this method, you can keep adding more properties to later call toString() 379 * again and get a more complete representation of the same object; but properties cannot be 380 * removed, so this only allows limited reuse of the helper instance. The helper allows 381 * duplication of properties (multiple name/value pairs with the same name can be added). 382 */ 383 @Override 384 public String toString() { 385 // create a copy to keep it consistent in case value changes 386 boolean omitNullValuesSnapshot = omitNullValues; 387 boolean omitEmptyValuesSnapshot = omitEmptyValues; 388 String nextSeparator = ""; 389 StringBuilder builder = new StringBuilder(32).append(className).append('{'); 390 for (ValueHolder valueHolder = holderHead.next; 391 valueHolder != null; 392 valueHolder = valueHolder.next) { 393 Object value = valueHolder.value; 394 if (valueHolder instanceof UnconditionalValueHolder 395 || (value == null 396 ? !omitNullValuesSnapshot 397 : (!omitEmptyValuesSnapshot || !isEmpty(value)))) { 398 builder.append(nextSeparator); 399 nextSeparator = ", "; 400 401 if (valueHolder.name != null) { 402 builder.append(valueHolder.name).append('='); 403 } 404 if (value != null && value.getClass().isArray()) { 405 Object[] objectArray = {value}; 406 String arrayString = Arrays.deepToString(objectArray); 407 builder.append(arrayString, 1, arrayString.length() - 1); 408 } else { 409 builder.append(value); 410 } 411 } 412 } 413 return builder.append('}').toString(); 414 } 415 416 private ValueHolder addHolder() { 417 ValueHolder valueHolder = new ValueHolder(); 418 holderTail = holderTail.next = valueHolder; 419 return valueHolder; 420 } 421 422 private ToStringHelper addHolder(@CheckForNull Object value) { 423 ValueHolder valueHolder = addHolder(); 424 valueHolder.value = value; 425 return this; 426 } 427 428 private ToStringHelper addHolder(String name, @CheckForNull Object value) { 429 ValueHolder valueHolder = addHolder(); 430 valueHolder.value = value; 431 valueHolder.name = checkNotNull(name); 432 return this; 433 } 434 435 private UnconditionalValueHolder addUnconditionalHolder() { 436 UnconditionalValueHolder valueHolder = new UnconditionalValueHolder(); 437 holderTail = holderTail.next = valueHolder; 438 return valueHolder; 439 } 440 441 private ToStringHelper addUnconditionalHolder(Object value) { 442 UnconditionalValueHolder valueHolder = addUnconditionalHolder(); 443 valueHolder.value = value; 444 return this; 445 } 446 447 private ToStringHelper addUnconditionalHolder(String name, Object value) { 448 UnconditionalValueHolder valueHolder = addUnconditionalHolder(); 449 valueHolder.value = value; 450 valueHolder.name = checkNotNull(name); 451 return this; 452 } 453 454 // Holder object for values that might be null and/or empty. 455 private static class ValueHolder { 456 @CheckForNull String name; 457 @CheckForNull Object value; 458 @CheckForNull ValueHolder next; 459 } 460 461 /** 462 * Holder object for values that cannot be null or empty (will be printed unconditionally). This 463 * helps to shortcut most calls to isEmpty(), which is important because the check for emptiness 464 * is relatively expensive. Use a subtype so this also doesn't need any extra storage. 465 */ 466 private static final class UnconditionalValueHolder extends ValueHolder {} 467 } 468 469 private MoreObjects() {} 470}