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