Path: blob/v3_openjdk/jre_lwjgl3glfw/src/main/java/android/util/Objects.java
2129 views
/*1* Copyright (C) 2010 The Android Open Source Project2*3* Licensed under the Apache License, Version 2.0 (the "License");4* you may not use this file except in compliance with the License.5* You may obtain a copy of the License at6*7* http://www.apache.org/licenses/LICENSE-2.08*9* Unless required by applicable law or agreed to in writing, software10* distributed under the License is distributed on an "AS IS" BASIS,11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12* See the License for the specific language governing permissions and13* limitations under the License.14*/15package android.util;16import java.lang.reflect.Field;17import java.lang.reflect.Modifier;18import java.util.Arrays;19public final class Objects {20private Objects() {}21/**22* Returns true if two possibly-null objects are equal.23*/24public static boolean equal(Object a, Object b) {25return a == b || (a != null && a.equals(b));26}27public static int hashCode(Object o) {28return (o == null) ? 0 : o.hashCode();29}30/**31* Returns a string reporting the value of each declared field, via reflection.32* Static and transient fields are automatically skipped. Produces output like33* "SimpleClassName[integer=1234,string="hello",character='c',intArray=[1,2,3]]".34*/35public static String toString(Object o) {36Class<?> c = o.getClass();37StringBuilder sb = new StringBuilder();38sb.append(c.getSimpleName()).append('[');39int i = 0;40for (Field f : c.getDeclaredFields()) {41if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0) {42continue;43}44f.setAccessible(true);45try {46Object value = f.get(o);47if (i++ > 0) {48sb.append(',');49}50sb.append(f.getName());51sb.append('=');52if (value.getClass().isArray()) {53if (value.getClass() == boolean[].class) {54sb.append(Arrays.toString((boolean[]) value));55} else if (value.getClass() == byte[].class) {56sb.append(Arrays.toString((byte[]) value));57} else if (value.getClass() == char[].class) {58sb.append(Arrays.toString((char[]) value));59} else if (value.getClass() == double[].class) {60sb.append(Arrays.toString((double[]) value));61} else if (value.getClass() == float[].class) {62sb.append(Arrays.toString((float[]) value));63} else if (value.getClass() == int[].class) {64sb.append(Arrays.toString((int[]) value));65} else if (value.getClass() == long[].class) {66sb.append(Arrays.toString((long[]) value));67} else if (value.getClass() == short[].class) {68sb.append(Arrays.toString((short[]) value));69} else {70sb.append(Arrays.toString((Object[]) value));71}72} else if (value.getClass() == Character.class) {73sb.append('\'').append(value).append('\'');74} else if (value.getClass() == String.class) {75sb.append('"').append(value).append('"');76} else {77sb.append(value);78}79} catch (IllegalAccessException unexpected) {80throw new AssertionError(unexpected);81}82}83sb.append("]");84return sb.toString();85}86}878889