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