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 org.jspecify.annotations.Nullable; 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 042public final class MoreObjects { 043 /** 044 * Returns the first of two given parameters that is not {@code null}, if either is, or otherwise 045 * throws a {@link NullPointerException}. 046 * 047 * <p>To find the first non-null element in an iterable, use {@code Iterables.find(iterable, 048 * Predicates.notNull())}. For varargs, use {@code Iterables.find(Arrays.asList(a, b, c, ...), 049 * Predicates.notNull())}, static importing as necessary. 050 * 051 * <p><b>Note:</b> if {@code first} is represented as an {@link Optional}, this can be 052 * accomplished with {@link Optional#or(Object) first.or(second)}. That approach also allows for 053 * lazy evaluation of the fallback instance, using {@link Optional#or(Supplier) 054 * first.or(supplier)}. 055 * 056 * <p><b>Java 9 users:</b> use {@code java.util.Objects.requireNonNullElse(first, second)} 057 * instead. 058 * 059 * @return {@code first} if it is non-null; otherwise {@code second} if it is non-null 060 * @throws NullPointerException if both {@code first} and {@code second} are null 061 * @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}). 062 */ 063 public static <T> T firstNonNull(@Nullable T first, @Nullable T second) { 064 if (first != null) { 065 return first; 066 } 067 if (second != null) { 068 return second; 069 } 070 throw new NullPointerException("Both parameters are null"); 071 } 072 073 /** 074 * Creates an instance of {@link ToStringHelper}. 075 * 076 * <p>This is helpful for implementing {@link Object#toString()}. Specification by example: 077 * 078 * <pre>{@code 079 * // Returns "ClassName{}" 080 * MoreObjects.toStringHelper(this) 081 * .toString(); 082 * 083 * // Returns "ClassName{x=1}" 084 * MoreObjects.toStringHelper(this) 085 * .add("x", 1) 086 * .toString(); 087 * 088 * // Returns "MyObject{x=1}" 089 * MoreObjects.toStringHelper("MyObject") 090 * .add("x", 1) 091 * .toString(); 092 * 093 * // Returns "ClassName{x=1, y=foo}" 094 * MoreObjects.toStringHelper(this) 095 * .add("x", 1) 096 * .add("y", "foo") 097 * .toString(); 098 * 099 * // Returns "ClassName{x=1}" 100 * MoreObjects.toStringHelper(this) 101 * .omitNullValues() 102 * .add("x", 1) 103 * .add("y", null) 104 * .toString(); 105 * }</pre> 106 * 107 * <p>Note that in GWT, class names are often obfuscated. 108 * 109 * @param self the object to generate the string for (typically {@code this}), used only for its 110 * class name 111 * @since 18.0 (since 2.0 as {@code Objects.toStringHelper()}). 112 */ 113 public static ToStringHelper toStringHelper(Object self) { 114 return new ToStringHelper(self.getClass().getSimpleName()); 115 } 116 117 /** 118 * Creates an instance of {@link ToStringHelper} in the same manner as {@link 119 * #toStringHelper(Object)}, but using the simple name of {@code clazz} instead of using an 120 * instance's {@link Object#getClass()}. 121 * 122 * <p>Note that in GWT, class names are often obfuscated. 123 * 124 * @param clazz the {@link Class} of the instance 125 * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}). 126 */ 127 public static ToStringHelper toStringHelper(Class<?> clazz) { 128 return new ToStringHelper(clazz.getSimpleName()); 129 } 130 131 /** 132 * Creates an instance of {@link ToStringHelper} in the same manner as {@link 133 * #toStringHelper(Object)}, but using {@code className} instead of using an instance's {@link 134 * Object#getClass()}. 135 * 136 * @param className the name of the instance type 137 * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}). 138 */ 139 public static ToStringHelper toStringHelper(String className) { 140 return new ToStringHelper(className); 141 } 142 143 /** 144 * Support class for {@link MoreObjects#toStringHelper}. 145 * 146 * @author Jason Lee 147 * @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}). 148 */ 149 public static final class ToStringHelper { 150 private final String className; 151 private final ValueHolder holderHead = new ValueHolder(); 152 private ValueHolder holderTail = holderHead; 153 private boolean omitNullValues = false; 154 private boolean omitEmptyValues = false; 155 156 /** Use {@link MoreObjects#toStringHelper(Object)} to create an instance. */ 157 private ToStringHelper(String className) { 158 this.className = checkNotNull(className); 159 } 160 161 /** 162 * Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with null 163 * value. The order of calling this method, relative to the {@code add()}/{@code addValue()} 164 * methods, is not significant. 165 * 166 * @since 18.0 (since 12.0 as {@code Objects.ToStringHelper.omitNullValues()}). 167 */ 168 @CanIgnoreReturnValue 169 public ToStringHelper omitNullValues() { 170 omitNullValues = true; 171 return this; 172 } 173 174 /** 175 * Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with 176 * empty values. The order of calling this method, relative to the {@code add()}/{@code 177 * addValue()} methods, is not significant. 178 * 179 * <p><b>Note:</b> in general, code should assume that the string form returned by {@code 180 * ToStringHelper} for a given object may change. In particular, the list of types which are 181 * checked for emptiness is subject to change. We currently check {@code CharSequence}s, {@code 182 * Collection}s, {@code Map}s, optionals (including Guava's), and arrays. 183 * 184 * @since 33.4.0 185 */ 186 @CanIgnoreReturnValue 187 public ToStringHelper omitEmptyValues() { 188 omitEmptyValues = 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, @Nullable 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(@Nullable 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 the 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 @CanIgnoreReturnValue 423 private ToStringHelper addHolder(@Nullable Object value) { 424 ValueHolder valueHolder = addHolder(); 425 valueHolder.value = value; 426 return this; 427 } 428 429 @CanIgnoreReturnValue 430 private ToStringHelper addHolder(String name, @Nullable Object value) { 431 ValueHolder valueHolder = addHolder(); 432 valueHolder.value = value; 433 valueHolder.name = checkNotNull(name); 434 return this; 435 } 436 437 private UnconditionalValueHolder addUnconditionalHolder() { 438 UnconditionalValueHolder valueHolder = new UnconditionalValueHolder(); 439 holderTail = holderTail.next = valueHolder; 440 return valueHolder; 441 } 442 443 @CanIgnoreReturnValue 444 private ToStringHelper addUnconditionalHolder(Object value) { 445 UnconditionalValueHolder valueHolder = addUnconditionalHolder(); 446 valueHolder.value = value; 447 return this; 448 } 449 450 @CanIgnoreReturnValue 451 private ToStringHelper addUnconditionalHolder(String name, Object value) { 452 UnconditionalValueHolder valueHolder = addUnconditionalHolder(); 453 valueHolder.value = value; 454 valueHolder.name = checkNotNull(name); 455 return this; 456 } 457 458 // Holder object for values that might be null and/or empty. 459 static class ValueHolder { 460 @Nullable String name; 461 @Nullable Object value; 462 @Nullable ValueHolder next; 463 } 464 465 /** 466 * Holder object for values that cannot be null or empty (will be printed unconditionally). This 467 * helps to shortcut most calls to isEmpty(), which is important because the check for emptiness 468 * is relatively expensive. Use a subtype so this also doesn't need any extra storage. 469 */ 470 private static final class UnconditionalValueHolder extends ValueHolder {} 471 } 472 473 private MoreObjects() {} 474}