/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Arrays; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import com.google.common.annotations.GwtCompatible; /** * Helper functions that can operate on any {@code Object}. * *
* See the Guava User Guide on writing * {@code Object} methods with {@code Objects}. * * @author Laurence Gonsalves * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Objects { private Objects() { } /** * Determines whether two possibly-null objects are equal. Returns: * *
* This assumes that any non-null objects passed to this function conform to the * {@code equals()} contract. */ @CheckReturnValue public static boolean equal(@Nullable Object a, @Nullable Object b) { return a == b || (a != null && a.equals(b)); } /** * Generates a hash code for multiple values. The hash code is generated by * calling {@link Arrays#hashCode(Object[])}. Note that array arguments to this * method, with the exception of a single Object array, do not get any special * handling; their hash codes are based on identity and not contents. * *
* This is useful for implementing {@link Object#hashCode()}. For example, in an * object that has three properties, {@code x}, {@code y}, and {@code z}, one * could write: * *
* {@code * public int hashCode() { * return Objects.hashCode(getX(), getY(), getZ()); * }} ** *
* Warning: When a single object is supplied, the returned hash code does * not equal the hash code of that object. */ public static int hashCode(@Nullable Object... objects) { return Arrays.hashCode(objects); } /** * Creates an instance of {@link ToStringHelper}. * *
* This is helpful for implementing {@link Object#toString()}. Specification by * example: * *
* {@code * // Returns "ClassName{}" * Objects.toStringHelper(this) * .toString(); * * // Returns "ClassName{x=1}" * Objects.toStringHelper(this) * .add("x", 1) * .toString(); * * // Returns "MyObject{x=1}" * Objects.toStringHelper("MyObject") * .add("x", 1) * .toString(); * * // Returns "ClassName{x=1, y=foo}" * Objects.toStringHelper(this) * .add("x", 1) * .add("y", "foo") * .toString(); * * // Returns "ClassName{x=1}" * Objects.toStringHelper(this) * .omitNullValues() * .add("x", 1) * .add("y", null) * .toString(); * }} ** *
* Note that in GWT, class names are often obfuscated. * * @param self the object to generate the string for (typically {@code this}), * used only for its class name * @since 2.0 */ public static ToStringHelper toStringHelper(Object self) { return new ToStringHelper(simpleName(self.getClass())); } /** * Creates an instance of {@link ToStringHelper} in the same manner as * {@link Objects#toStringHelper(Object)}, but using the name of {@code clazz} * instead of using an instance's {@link Object#getClass()}. * *
* Note that in GWT, class names are often obfuscated. * * @param clazz the {@link Class} of the instance * @since 7.0 (source-compatible since 2.0) */ public static ToStringHelper toStringHelper(Class> clazz) { return new ToStringHelper(simpleName(clazz)); } /** * Creates an instance of {@link ToStringHelper} in the same manner as * {@link Objects#toStringHelper(Object)}, but using {@code className} instead * of using an instance's {@link Object#getClass()}. * * @param className the name of the instance type * @since 7.0 (source-compatible since 2.0) */ public static ToStringHelper toStringHelper(String className) { return new ToStringHelper(className); } /** * {@link Class#getSimpleName()} is not GWT compatible yet, so we provide our * own implementation. */ private static String simpleName(Class> clazz) { String name = clazz.getName(); // the nth anonymous class has a class name ending in "Outer$n" // and local inner classes have names ending in "Outer.$1Inner" name = name.replaceAll("\\$[0-9]+", "\\$"); // we want the name of the inner class all by its lonesome int start = name.lastIndexOf('$'); // if this isn't an inner class, just find the start of the // top level class name. if (start == -1) { start = name.lastIndexOf('.'); } return name.substring(start + 1); } /** * Returns the first of two given parameters that is not {@code null}, if either * is, or otherwise throws a {@link NullPointerException}. * *
* Note: if {@code first} is represented as an {@link Optional}, this can
* be accomplished with {@linkplain Optional#or(Object) first.or(second)}. That
* approach also allows for lazy evaluation of the fallback instance, using
* {@linkplain Optional#or(Supplier) first.or(Supplier)}.
*
* @return {@code first} if {@code first} is not {@code null}, or {@code second}
* if {@code first} is {@code null} and {@code second} is not
* {@code null}
* @throws NullPointerException if both {@code first} and {@code second} were
* {@code null}
* @since 3.0
*/
public static
* It is strongly encouraged to use {@link #add(String, Object)} instead and
* give value a readable name.
*/
public ToStringHelper addValue(@Nullable Object value) {
return addHolder(value);
}
/**
* Adds an unnamed value to the formatted output.
*
*
* It is strongly encouraged to use {@link #add(String, boolean)} instead and
* give value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(boolean value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
*
* It is strongly encouraged to use {@link #add(String, char)} instead and give
* value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(char value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
*
* It is strongly encouraged to use {@link #add(String, double)} instead and
* give value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(double value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
*
* It is strongly encouraged to use {@link #add(String, float)} instead and give
* value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(float value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
*
* It is strongly encouraged to use {@link #add(String, int)} instead and give
* value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(int value) {
return addHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
*
* It is strongly encouraged to use {@link #add(String, long)} instead and give
* value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(long value) {
return addHolder(String.valueOf(value));
}
/**
* Returns a string in the format specified by
* {@link Objects#toStringHelper(Object)}.
*
*
* After calling this method, you can keep adding more properties to later call
* toString() again and get a more complete representation of the same object;
* but properties cannot be removed, so this only allows limited reuse of the
* helper instance. The helper allows duplication of properties (multiple
* name/value pairs with the same name can be added).
*/
@Override
public String toString() {
// create a copy to keep it consistent in case value changes
boolean omitNullValuesSnapshot = omitNullValues;
String nextSeparator = "";
StringBuilder builder = new StringBuilder(32).append(className).append('{');
for (ValueHolder valueHolder = holderHead.next; valueHolder != null; valueHolder = valueHolder.next) {
if (!omitNullValuesSnapshot || valueHolder.value != null) {
builder.append(nextSeparator);
nextSeparator = ", ";
if (valueHolder.name != null) {
builder.append(valueHolder.name).append('=');
}
builder.append(valueHolder.value);
}
}
return builder.append('}').toString();
}
private ValueHolder addHolder() {
ValueHolder valueHolder = new ValueHolder();
holderTail = holderTail.next = valueHolder;
return valueHolder;
}
private ToStringHelper addHolder(@Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
return this;
}
private ToStringHelper addHolder(String name, @Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
valueHolder.name = checkNotNull(name);
return this;
}
private static final class ValueHolder {
String name;
Object value;
ValueHolder next;
}
}
}