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.qual.Nullable;
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   * @return {@code first} if it is non-null; otherwise {@code second} if it is non-null
051   * @throws NullPointerException if both {@code first} and {@code second} are null
052   * @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}).
053   */
054  public static <T> T firstNonNull(@Nullable T first, @Nullable T second) {
055    if (first != null) {
056      return first;
057    }
058    if (second != null) {
059      return second;
060    }
061    throw new NullPointerException("Both parameters are null");
062  }
063
064  /**
065   * Creates an instance of {@link ToStringHelper}.
066   *
067   * <p>This is helpful for implementing {@link Object#toString()}. Specification by example:
068   *
069   * <pre>{@code
070   * // Returns "ClassName{}"
071   * MoreObjects.toStringHelper(this)
072   *     .toString();
073   *
074   * // Returns "ClassName{x=1}"
075   * MoreObjects.toStringHelper(this)
076   *     .add("x", 1)
077   *     .toString();
078   *
079   * // Returns "MyObject{x=1}"
080   * MoreObjects.toStringHelper("MyObject")
081   *     .add("x", 1)
082   *     .toString();
083   *
084   * // Returns "ClassName{x=1, y=foo}"
085   * MoreObjects.toStringHelper(this)
086   *     .add("x", 1)
087   *     .add("y", "foo")
088   *     .toString();
089   *
090   * // Returns "ClassName{x=1}"
091   * MoreObjects.toStringHelper(this)
092   *     .omitNullValues()
093   *     .add("x", 1)
094   *     .add("y", null)
095   *     .toString();
096   * }</pre>
097   *
098   * <p>Note that in GWT, class names are often obfuscated.
099   *
100   * @param self the object to generate the string for (typically {@code this}), used only for its
101   *     class name
102   * @since 18.0 (since 2.0 as {@code Objects.toStringHelper()}).
103   */
104  public static ToStringHelper toStringHelper(Object self) {
105    return new ToStringHelper(self.getClass().getSimpleName());
106  }
107
108  /**
109   * Creates an instance of {@link ToStringHelper} in the same manner as {@link
110   * #toStringHelper(Object)}, but using the simple name of {@code clazz} instead of using an
111   * instance's {@link Object#getClass()}.
112   *
113   * <p>Note that in GWT, class names are often obfuscated.
114   *
115   * @param clazz the {@link Class} of the instance
116   * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
117   */
118  public static ToStringHelper toStringHelper(Class<?> clazz) {
119    return new ToStringHelper(clazz.getSimpleName());
120  }
121
122  /**
123   * Creates an instance of {@link ToStringHelper} in the same manner as {@link
124   * #toStringHelper(Object)}, but using {@code className} instead of using an instance's {@link
125   * Object#getClass()}.
126   *
127   * @param className the name of the instance type
128   * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
129   */
130  public static ToStringHelper toStringHelper(String className) {
131    return new ToStringHelper(className);
132  }
133
134  /**
135   * Support class for {@link MoreObjects#toStringHelper}.
136   *
137   * @author Jason Lee
138   * @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}).
139   */
140  public static final class ToStringHelper {
141    private final String className;
142    private final ValueHolder holderHead = new ValueHolder();
143    private ValueHolder holderTail = holderHead;
144    private boolean omitNullValues = false;
145
146    /** Use {@link MoreObjects#toStringHelper(Object)} to create an instance. */
147    private ToStringHelper(String className) {
148      this.className = checkNotNull(className);
149    }
150
151    /**
152     * Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with null
153     * value. The order of calling this method, relative to the {@code add()}/{@code addValue()}
154     * methods, is not significant.
155     *
156     * @since 18.0 (since 12.0 as {@code Objects.ToStringHelper.omitNullValues()}).
157     */
158    @CanIgnoreReturnValue
159    public ToStringHelper omitNullValues() {
160      omitNullValues = true;
161      return this;
162    }
163
164    /**
165     * Adds a name/value pair to the formatted output in {@code name=value} format. If {@code value}
166     * is {@code null}, the string {@code "null"} is used, unless {@link #omitNullValues()} is
167     * called, in which case this name/value pair will not be added.
168     */
169    @CanIgnoreReturnValue
170    public ToStringHelper add(String name, @Nullable Object value) {
171      return addHolder(name, value);
172    }
173
174    /**
175     * Adds a name/value pair to the formatted output in {@code name=value} format.
176     *
177     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
178     */
179    @CanIgnoreReturnValue
180    public ToStringHelper add(String name, boolean value) {
181      return addHolder(name, String.valueOf(value));
182    }
183
184    /**
185     * Adds a name/value pair to the formatted output in {@code name=value} format.
186     *
187     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
188     */
189    @CanIgnoreReturnValue
190    public ToStringHelper add(String name, char value) {
191      return addHolder(name, String.valueOf(value));
192    }
193
194    /**
195     * Adds a name/value pair to the formatted output in {@code name=value} format.
196     *
197     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
198     */
199    @CanIgnoreReturnValue
200    public ToStringHelper add(String name, double value) {
201      return addHolder(name, String.valueOf(value));
202    }
203
204    /**
205     * Adds a name/value pair to the formatted output in {@code name=value} format.
206     *
207     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
208     */
209    @CanIgnoreReturnValue
210    public ToStringHelper add(String name, float value) {
211      return addHolder(name, String.valueOf(value));
212    }
213
214    /**
215     * Adds a name/value pair to the formatted output in {@code name=value} format.
216     *
217     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
218     */
219    @CanIgnoreReturnValue
220    public ToStringHelper add(String name, int value) {
221      return addHolder(name, String.valueOf(value));
222    }
223
224    /**
225     * Adds a name/value pair to the formatted output in {@code name=value} format.
226     *
227     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
228     */
229    @CanIgnoreReturnValue
230    public ToStringHelper add(String name, long value) {
231      return addHolder(name, String.valueOf(value));
232    }
233
234    /**
235     * Adds an unnamed value to the formatted output.
236     *
237     * <p>It is strongly encouraged to use {@link #add(String, Object)} instead and give value a
238     * readable name.
239     */
240    @CanIgnoreReturnValue
241    public ToStringHelper addValue(@Nullable Object value) {
242      return addHolder(value);
243    }
244
245    /**
246     * Adds an unnamed value to the formatted output.
247     *
248     * <p>It is strongly encouraged to use {@link #add(String, boolean)} instead and give value a
249     * readable name.
250     *
251     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
252     */
253    @CanIgnoreReturnValue
254    public ToStringHelper addValue(boolean value) {
255      return addHolder(String.valueOf(value));
256    }
257
258    /**
259     * Adds an unnamed value to the formatted output.
260     *
261     * <p>It is strongly encouraged to use {@link #add(String, char)} instead and give value a
262     * readable name.
263     *
264     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
265     */
266    @CanIgnoreReturnValue
267    public ToStringHelper addValue(char value) {
268      return addHolder(String.valueOf(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, double)} 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(double value) {
281      return addHolder(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, float)} 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(float value) {
294      return addHolder(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, int)} 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(int value) {
307      return addHolder(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, long)} 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(long value) {
320      return addHolder(String.valueOf(value));
321    }
322
323    /**
324     * Returns a string in the format specified by {@link MoreObjects#toStringHelper(Object)}.
325     *
326     * <p>After calling this method, you can keep adding more properties to later call toString()
327     * again and get a more complete representation of the same object; but properties cannot be
328     * removed, so this only allows limited reuse of the helper instance. The helper allows
329     * duplication of properties (multiple name/value pairs with the same name can be added).
330     */
331    @Override
332    public String toString() {
333      // create a copy to keep it consistent in case value changes
334      boolean omitNullValuesSnapshot = omitNullValues;
335      String nextSeparator = "";
336      StringBuilder builder = new StringBuilder(32).append(className).append('{');
337      for (ValueHolder valueHolder = holderHead.next;
338          valueHolder != null;
339          valueHolder = valueHolder.next) {
340        Object value = valueHolder.value;
341        if (!omitNullValuesSnapshot || value != null) {
342          builder.append(nextSeparator);
343          nextSeparator = ", ";
344
345          if (valueHolder.name != null) {
346            builder.append(valueHolder.name).append('=');
347          }
348          if (value != null && value.getClass().isArray()) {
349            Object[] objectArray = {value};
350            String arrayString = Arrays.deepToString(objectArray);
351            builder.append(arrayString, 1, arrayString.length() - 1);
352          } else {
353            builder.append(value);
354          }
355        }
356      }
357      return builder.append('}').toString();
358    }
359
360    private ValueHolder addHolder() {
361      ValueHolder valueHolder = new ValueHolder();
362      holderTail = holderTail.next = valueHolder;
363      return valueHolder;
364    }
365
366    private ToStringHelper addHolder(@Nullable Object value) {
367      ValueHolder valueHolder = addHolder();
368      valueHolder.value = value;
369      return this;
370    }
371
372    private ToStringHelper addHolder(String name, @Nullable Object value) {
373      ValueHolder valueHolder = addHolder();
374      valueHolder.value = value;
375      valueHolder.name = checkNotNull(name);
376      return this;
377    }
378
379    private static final class ValueHolder {
380      @Nullable String name;
381      @Nullable Object value;
382      @Nullable ValueHolder next;
383    }
384  }
385
386  private MoreObjects() {}
387}