Java/Class/toString
Содержание
- 1 Array To String
- 2 Constructs pretty string representation of object value
- 3 Demonstrate toString() without an override
- 4 Gets the toString of an Object returning an empty string ("") if null input.
- 5 Gets the toString that would be produced by Object if a class did not override toString itself.
- 6 Null Safe To String
- 7 Reflection based toString() utilities
- 8 ShowToString -- demo program to show default toString methods
- 9 To String Demo
- 10 ToString -- demo program to show a toString method
- 11 toString(Object[] array)
- 12 Use a generic toString()
Array To String
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Collection;
/**
* General string utils
*/
public class StringUtils {
final public static char COMMA = ",";
final public static String COMMA_STR = ",";
final public static char ESCAPE_CHAR = "\\";
private static DecimalFormat oneDecimal = new DecimalFormat("0.0");
/**
* Given an array of strings, return a comma-separated list of its elements.
* @param strs Array of strings
* @return Empty string if strs.length is 0, comma separated list of strings
* otherwise
*/
public static String arrayToString(String[] strs) {
if (strs.length == 0) { return ""; }
StringBuffer sbuf = new StringBuffer();
sbuf.append(strs[0]);
for (int idx = 1; idx < strs.length; idx++) {
sbuf.append(",");
sbuf.append(strs[idx]);
}
return sbuf.toString();
}
}
Constructs pretty string representation of object value
// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* Constructs pretty string representation of object value.
*/
public class PrettyStringBuilder {
protected int maxArrayLen = 10;
protected int maxDeep = 3;
protected int deep;
protected String nullValue = "<null>";
public PrettyStringBuilder() {
}
public int getMaxArrayLen() {
return maxArrayLen;
}
public void setMaxArrayLen(int maxArrayLen) {
this.maxArrayLen = maxArrayLen;
}
public int getMaxDeep() {
return maxDeep;
}
public void setMaxDeep(int maxDeep) {
this.maxDeep = maxDeep;
}
public String getNullValue() {
return nullValue;
}
public void setNullValue(String nullValue) {
this.nullValue = nullValue;
}
/**
* Returns pretty value from object value.
*/
protected String toPrettyString(Object obj) {
deep++;
if (obj == null) {
deep--;
return nullValue;
}
if (deep == maxDeep) {
deep--;
return obj.toString();
}
StringBuilder s = new StringBuilder();
Class c = obj.getClass();
if (c.isArray()) {
int arrayLen = Array.getLength(obj);
int len = Math.min(arrayLen, maxArrayLen);
s.append("[");
for (int i = 0; i < len; i++) {
s.append(toPrettyString(Array.get(obj, i)));
if (i != len - 1) {
s.append(",");
}
}
if (len < arrayLen) {
s.append("...");
}
s.append("]");
} else if (obj instanceof Collection) {
Collection coll = (Collection) obj;
Iterator it = coll.iterator();
int i = 0;
s.append("(");
while ((it.hasNext() && (i < maxArrayLen))) {
s.append(toPrettyString(it.next()));
i++;
}
if (i < coll.size()) {
s.append("...");
}
s.append(")");
} else if (obj instanceof Map) {
Map map = (Map) obj;
Iterator it = map.keySet().iterator();
int i = 0;
s.append("{");
while ((it.hasNext() && (i < maxArrayLen))) {
Object key = it.next();
s.append(key).append(":");
s.append(toPrettyString(map.get(key)));
i++;
}
if (i < map.size()) {
s.append("...");
}
s.append("}");
} else {
s.append(obj.toString());
}
deep--;
return s.toString();
}
/**
* Returns pretty string representation of the object.
*/
public String toString(Object value) {
return toPrettyString(value);
}
}
Demonstrate toString() without an override
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
/* Demonstrate toString() without an override */
public class ToStringWithout {
int x, y;
/** Simple constructor */
public ToStringWithout(int anX, int aY) {
x = anX; y = aY;
}
/** Main just creates and prints an object */
public static void main(String[] args) {
System.out.println(new ToStringWithout(42, 86));
}
}
Gets the toString of an Object returning an empty string ("") if null input.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
import java.io.Serializable;
/**
* <p>Operations on <code>Object</code>.</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will generally not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.</p>
*
* @author
* @since 1.0
* @version $Id: ObjectUtils.java 594336 2007-11-12 22:54:02Z bayard $
*/
public class ObjectUtils {
/**
* <p>Singleton used as a <code>null</code> placeholder where
* <code>null</code> has another meaning.</p>
*
* <p>For example, in a <code>HashMap</code> the
* {@link java.util.HashMap#get(java.lang.Object)} method returns
* <code>null</code> if the <code>Map</code> contains
* <code>null</code> or if there is no matching key. The
* <code>Null</code> placeholder can be used to distinguish between
* these two cases.</p>
*
* <p>Another example is <code>Hashtable</code>, where <code>null</code>
* cannot be stored.</p>
*
* <p>This instance is Serializable.</p>
*/
public static final Null NULL = new Null();
/**
* <p><code>ObjectUtils</code> instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* <code>ObjectUtils.defaultIfNull("a","b");</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public ObjectUtils() {
super();
}
// Defaulting
//-----------------------------------------------------------------------
/**
* <p>Returns a default value if the object passed is
* <code>null</code>.</p>
*
* <pre>
* ObjectUtils.defaultIfNull(null, null) = null
* ObjectUtils.defaultIfNull(null, "") = ""
* ObjectUtils.defaultIfNull(null, "zz") = "zz"
* ObjectUtils.defaultIfNull("abc", *) = "abc"
* ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
* </pre>
*
* @param object the <code>Object</code> to test, may be <code>null</code>
* @param defaultValue the default value to return, may be <code>null</code>
* @return <code>object</code> if it is not <code>null</code>, defaultValue otherwise
*/
public static Object defaultIfNull(Object object, Object defaultValue) {
return object != null ? object : defaultValue;
}
/**
* <p>Compares two objects for equality, where either one or both
* objects may be <code>null</code>.</p>
*
* <pre>
* ObjectUtils.equals(null, null) = true
* ObjectUtils.equals(null, "") = false
* ObjectUtils.equals("", null) = false
* ObjectUtils.equals("", "") = true
* ObjectUtils.equals(Boolean.TRUE, null) = false
* ObjectUtils.equals(Boolean.TRUE, "true") = false
* ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true
* ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
* </pre>
*
* @param object1 the first object, may be <code>null</code>
* @param object2 the second object, may be <code>null</code>
* @return <code>true</code> if the values of both objects are the same
*/
public static boolean equals(Object object1, Object object2) {
if (object1 == object2) {
return true;
}
if ((object1 == null) || (object2 == null)) {
return false;
}
return object1.equals(object2);
}
/**
* <p>Gets the hash code of an object returning zero when the
* object is <code>null</code>.</p>
*
* <pre>
* ObjectUtils.hashCode(null) = 0
* ObjectUtils.hashCode(obj) = obj.hashCode()
* </pre>
*
* @param obj the object to obtain the hash code of, may be <code>null</code>
* @return the hash code of the object, or zero if null
* @since 2.1
*/
public static int hashCode(Object obj) {
return (obj == null) ? 0 : obj.hashCode();
}
// Identity ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the toString that would be produced by <code>Object</code>
* if a class did not override toString itself. <code>null</code>
* will return <code>null</code>.</p>
*
* <pre>
* ObjectUtils.identityToString(null) = null
* ObjectUtils.identityToString("") = "java.lang.String@1e23"
* ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
* </pre>
*
* @param object the object to create a toString for, may be
* <code>null</code>
* @return the default toString text, or <code>null</code> if
* <code>null</code> passed in
*/
public static String identityToString(Object object) {
if (object == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
identityToString(buffer, object);
return buffer.toString();
}
/**
* <p>Appends the toString that would be produced by <code>Object</code>
* if a class did not override toString itself. <code>null</code>
* will throw a NullPointerException for either of the two parameters. </p>
*
* <pre>
* ObjectUtils.identityToString(buf, "") = buf.append("java.lang.String@1e23"
* ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa"
* ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa")
* </pre>
*
* @param buffer the buffer to append to
* @param object the object to create a toString for
* @since 2.4
*/
public static void identityToString(StringBuffer buffer, Object object) {
if (object == null) {
throw new NullPointerException("Cannot get the toString of a null identity");
}
buffer.append(object.getClass().getName())
.append("@")
.append(Integer.toHexString(System.identityHashCode(object)));
}
// ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the <code>toString</code> of an <code>Object</code> returning
* an empty string ("") if <code>null</code> input.</p>
*
* <pre>
* ObjectUtils.toString(null) = ""
* ObjectUtils.toString("") = ""
* ObjectUtils.toString("bat") = "bat"
* ObjectUtils.toString(Boolean.TRUE) = "true"
* </pre>
*
* @see StringUtils#defaultString(String)
* @see String#valueOf(Object)
* @param obj the Object to <code>toString</code>, may be null
* @return the passed in Object"s toString, or nullStr if <code>null</code> input
* @since 2.0
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
/**
* <p>Gets the <code>toString</code> of an <code>Object</code> returning
* a specified text if <code>null</code> input.</p>
*
* <pre>
* ObjectUtils.toString(null, null) = null
* ObjectUtils.toString(null, "null") = "null"
* ObjectUtils.toString("", "null") = ""
* ObjectUtils.toString("bat", "null") = "bat"
* ObjectUtils.toString(Boolean.TRUE, "null") = "true"
* </pre>
*
* @see StringUtils#defaultString(String,String)
* @see String#valueOf(Object)
* @param obj the Object to <code>toString</code>, may be null
* @param nullStr the String to return if <code>null</code> input, may be null
* @return the passed in Object"s toString, or nullStr if <code>null</code> input
* @since 2.0
*/
public static String toString(Object obj, String nullStr) {
return obj == null ? nullStr : obj.toString();
}
// Null
//-----------------------------------------------------------------------
/**
* <p>Class used as a null placeholder where <code>null</code>
* has another meaning.</p>
*
* <p>For example, in a <code>HashMap</code> the
* {@link java.util.HashMap#get(java.lang.Object)} method returns
* <code>null</code> if the <code>Map</code> contains
* <code>null</code> or if there is no matching key. The
* <code>Null</code> placeholder can be used to distinguish between
* these two cases.</p>
*
* <p>Another example is <code>Hashtable</code>, where <code>null</code>
* cannot be stored.</p>
*/
public static class Null implements Serializable {
/**
* Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 7092611880189329093L;
/**
* Restricted constructor - singleton.
*/
Null() {
super();
}
/**
* <p>Ensure singleton.</p>
*
* @return the singleton value
*/
private Object readResolve() {
return ObjectUtils.NULL;
}
}
}
Gets the toString that would be produced by Object if a class did not override toString itself.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
import java.io.Serializable;
/**
* <p>Operations on <code>Object</code>.</p>
*
* <p>This class tries to handle <code>null</code> input gracefully.
* An exception will generally not be thrown for a <code>null</code> input.
* Each method documents its behaviour in more detail.</p>
*
* @author
* @since 1.0
* @version $Id: ObjectUtils.java 594336 2007-11-12 22:54:02Z bayard $
*/
public class ObjectUtils {
/**
* <p>Singleton used as a <code>null</code> placeholder where
* <code>null</code> has another meaning.</p>
*
* <p>For example, in a <code>HashMap</code> the
* {@link java.util.HashMap#get(java.lang.Object)} method returns
* <code>null</code> if the <code>Map</code> contains
* <code>null</code> or if there is no matching key. The
* <code>Null</code> placeholder can be used to distinguish between
* these two cases.</p>
*
* <p>Another example is <code>Hashtable</code>, where <code>null</code>
* cannot be stored.</p>
*
* <p>This instance is Serializable.</p>
*/
public static final Null NULL = new Null();
/**
* <p><code>ObjectUtils</code> instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* <code>ObjectUtils.defaultIfNull("a","b");</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public ObjectUtils() {
super();
}
// Defaulting
//-----------------------------------------------------------------------
/**
* <p>Returns a default value if the object passed is
* <code>null</code>.</p>
*
* <pre>
* ObjectUtils.defaultIfNull(null, null) = null
* ObjectUtils.defaultIfNull(null, "") = ""
* ObjectUtils.defaultIfNull(null, "zz") = "zz"
* ObjectUtils.defaultIfNull("abc", *) = "abc"
* ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
* </pre>
*
* @param object the <code>Object</code> to test, may be <code>null</code>
* @param defaultValue the default value to return, may be <code>null</code>
* @return <code>object</code> if it is not <code>null</code>, defaultValue otherwise
*/
public static Object defaultIfNull(Object object, Object defaultValue) {
return object != null ? object : defaultValue;
}
/**
* <p>Compares two objects for equality, where either one or both
* objects may be <code>null</code>.</p>
*
* <pre>
* ObjectUtils.equals(null, null) = true
* ObjectUtils.equals(null, "") = false
* ObjectUtils.equals("", null) = false
* ObjectUtils.equals("", "") = true
* ObjectUtils.equals(Boolean.TRUE, null) = false
* ObjectUtils.equals(Boolean.TRUE, "true") = false
* ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true
* ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
* </pre>
*
* @param object1 the first object, may be <code>null</code>
* @param object2 the second object, may be <code>null</code>
* @return <code>true</code> if the values of both objects are the same
*/
public static boolean equals(Object object1, Object object2) {
if (object1 == object2) {
return true;
}
if ((object1 == null) || (object2 == null)) {
return false;
}
return object1.equals(object2);
}
/**
* <p>Gets the hash code of an object returning zero when the
* object is <code>null</code>.</p>
*
* <pre>
* ObjectUtils.hashCode(null) = 0
* ObjectUtils.hashCode(obj) = obj.hashCode()
* </pre>
*
* @param obj the object to obtain the hash code of, may be <code>null</code>
* @return the hash code of the object, or zero if null
* @since 2.1
*/
public static int hashCode(Object obj) {
return (obj == null) ? 0 : obj.hashCode();
}
// Identity ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the toString that would be produced by <code>Object</code>
* if a class did not override toString itself. <code>null</code>
* will return <code>null</code>.</p>
*
* <pre>
* ObjectUtils.identityToString(null) = null
* ObjectUtils.identityToString("") = "java.lang.String@1e23"
* ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
* </pre>
*
* @param object the object to create a toString for, may be
* <code>null</code>
* @return the default toString text, or <code>null</code> if
* <code>null</code> passed in
*/
public static String identityToString(Object object) {
if (object == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
identityToString(buffer, object);
return buffer.toString();
}
/**
* <p>Appends the toString that would be produced by <code>Object</code>
* if a class did not override toString itself. <code>null</code>
* will throw a NullPointerException for either of the two parameters. </p>
*
* <pre>
* ObjectUtils.identityToString(buf, "") = buf.append("java.lang.String@1e23"
* ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa"
* ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa")
* </pre>
*
* @param buffer the buffer to append to
* @param object the object to create a toString for
* @since 2.4
*/
public static void identityToString(StringBuffer buffer, Object object) {
if (object == null) {
throw new NullPointerException("Cannot get the toString of a null identity");
}
buffer.append(object.getClass().getName())
.append("@")
.append(Integer.toHexString(System.identityHashCode(object)));
}
// ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the <code>toString</code> of an <code>Object</code> returning
* an empty string ("") if <code>null</code> input.</p>
*
* <pre>
* ObjectUtils.toString(null) = ""
* ObjectUtils.toString("") = ""
* ObjectUtils.toString("bat") = "bat"
* ObjectUtils.toString(Boolean.TRUE) = "true"
* </pre>
*
* @see StringUtils#defaultString(String)
* @see String#valueOf(Object)
* @param obj the Object to <code>toString</code>, may be null
* @return the passed in Object"s toString, or nullStr if <code>null</code> input
* @since 2.0
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
/**
* <p>Gets the <code>toString</code> of an <code>Object</code> returning
* a specified text if <code>null</code> input.</p>
*
* <pre>
* ObjectUtils.toString(null, null) = null
* ObjectUtils.toString(null, "null") = "null"
* ObjectUtils.toString("", "null") = ""
* ObjectUtils.toString("bat", "null") = "bat"
* ObjectUtils.toString(Boolean.TRUE, "null") = "true"
* </pre>
*
* @see StringUtils#defaultString(String,String)
* @see String#valueOf(Object)
* @param obj the Object to <code>toString</code>, may be null
* @param nullStr the String to return if <code>null</code> input, may be null
* @return the passed in Object"s toString, or nullStr if <code>null</code> input
* @since 2.0
*/
public static String toString(Object obj, String nullStr) {
return obj == null ? nullStr : obj.toString();
}
// Null
//-----------------------------------------------------------------------
/**
* <p>Class used as a null placeholder where <code>null</code>
* has another meaning.</p>
*
* <p>For example, in a <code>HashMap</code> the
* {@link java.util.HashMap#get(java.lang.Object)} method returns
* <code>null</code> if the <code>Map</code> contains
* <code>null</code> or if there is no matching key. The
* <code>Null</code> placeholder can be used to distinguish between
* these two cases.</p>
*
* <p>Another example is <code>Hashtable</code>, where <code>null</code>
* cannot be stored.</p>
*/
public static class Null implements Serializable {
/**
* Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 7092611880189329093L;
/**
* Restricted constructor - singleton.
*/
Null() {
super();
}
/**
* <p>Ensure singleton.</p>
*
* @return the singleton value
*/
private Object readResolve() {
return ObjectUtils.NULL;
}
}
}
Null Safe To String
import java.lang.reflect.Array;
import java.util.Arrays;
/*
* Copyright 2002-2007 the original author or 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.
*/
//Revised from springframework
/**
* Miscellaneous object utility methods. Mainly for internal use within the
* framework; consider Jakarta"s Commons Lang for a more comprehensive suite
* of object utilities.
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @author Alex Ruiz
* @since 19.03.2004
* @see org.apache.rumons.lang.ObjectUtils
*/
abstract class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* Return a content-based String representation if <code>obj</code> is
* not <code>null</code>; otherwise returns an empty String.
* <p>Differs from {@link #nullSafeToString(Object)} in that it returns
* an empty String rather than "null" for a <code>null</code> value.
* @param obj the object to build a display String for
* @return a display String representation of <code>obj</code>
* @see #nullSafeToString(Object)
*/
public static String getDisplayString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return nullSafeToString(obj);
}
/**
* Determine the class name for the given object.
* <p>Returns <code>"null"</code> if <code>obj</code> is <code>null</code>.
* @param obj the object to introspect (may be <code>null</code>)
* @return the corresponding class name
*/
public static String nullSafeClassName(Object obj) {
return (obj != null ? obj.getClass().getName() : NULL_STRING);
}
/**
* Return a String representation of the specified Object.
* <p>Builds a String representation of the contents in case of an array.
* Returns <code>"null"</code> if <code>obj</code> is <code>null</code>.
* @param obj the object to build a String representation for
* @return a String representation of <code>obj</code>
*/
public static String nullSafeToString(Object obj) {
if (obj == null) {
return NULL_STRING;
}
if (obj instanceof String) {
return (String) obj;
}
if (obj instanceof Object[]) {
return nullSafeToString((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeToString((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeToString((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeToString((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeToString((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeToString((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeToString((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeToString((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeToString((short[]) obj);
}
String str = obj.toString();
return (str != null ? str : EMPTY_STRING);
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(Object[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(String.valueOf(array[i]));
}
buffer.append(ARRAY_END);
return buffer.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(boolean[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(array[i]);
}
buffer.append(ARRAY_END);
return buffer.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(byte[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(array[i]);
}
buffer.append(ARRAY_END);
return buffer.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(char[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(""").append(array[i]).append(""");
}
buffer.append(ARRAY_END);
return buffer.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(double[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(array[i]);
}
buffer.append(ARRAY_END);
return buffer.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(float[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(array[i]);
}
buffer.append(ARRAY_END);
return buffer.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(int[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(array[i]);
}
buffer.append(ARRAY_END);
return buffer.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(long[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(array[i]);
}
buffer.append(ARRAY_END);
return buffer.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array"s elements,
* enclosed in curly braces (<code>"{}"</code>). Adjacent elements are separated
* by the characters <code>", "</code> (a comma followed by a space). Returns
* <code>"null"</code> if <code>array</code> is <code>null</code>.
* @param array the array to build a String representation for
* @return a String representation of <code>array</code>
*/
public static String nullSafeToString(short[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
if (i == 0) {
buffer.append(ARRAY_START);
}
else {
buffer.append(ARRAY_ELEMENT_SEPARATOR);
}
buffer.append(array[i]);
}
buffer.append(ARRAY_END);
return buffer.toString();
}
}
Reflection based toString() utilities
import java.lang.reflect.Field;
public class Main {
String hello = "world";
int i = 42;
public static void main(String args[]) {
System.out.println(Util.toString(new MyClass()));
System.out.println(Util.toString(new MyAnotherClass()));
}
}
class Util {
public static String toString(Object o) {
StringBuilder sb = new StringBuilder();
toString(o, o.getClass(), sb);
return o.getClass().getName()+ "\n"+sb.toString();
}
private static void toString(Object o, Class clazz, StringBuilder sb) {
Field f[] = clazz.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
f[i].setAccessible(true);
try {
sb.append(f[i].getName() + "=" + f[i].get(o)+"\n");
} catch (Exception e) {
e.printStackTrace();
}
}
if (clazz.getSuperclass() != null)
toString(o, clazz.getSuperclass(), sb);
}
}
class MyClass {
int i = 1;
private double d = 3.14;
}
class MyAnotherClass extends MyClass{
int f = 9;
}
ShowToString -- demo program to show default toString methods
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.util.*;
import java.awt.Button;
/**
* ShowToString -- demo program to show default toString methods.
* Some classes provide a toString() method, while others inherit
* the default toString() from Object. In all cases, you can print
* an object by calling its toString(), which is very useful in debugging!
*/
public class ShowToString {
/** main method */
public static void main(String[] argv) {
System.out.println("An Object\t" + new Object());
System.out.println("A Date \t" + new Date());
System.out.println("A GregorianCalendar\t" + new GregorianCalendar());
System.out.println("An Exception\t" + new Exception("Hi!"));
Button b = new Button("Push ME!"); // An AWT pushbutton
b.setBounds(40, 50, 120, 60); // explained in the AWT chapter!
System.out.println("A Button\t" + b);
System.out.println("A ShowToString object!\t" + new ShowToString());
}
}
To String Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
public class ToStringDemo {
public static void main(String[] args) {
double d = 858.48;
String s = Double.toString(d);
int dot = s.indexOf(".");
System.out.println(s.substring(0, dot).length()
+ " digits before decimal point.");
System.out.println(s.substring(dot + 1).length()
+ " digits after decimal point.");
}
}
ToString -- demo program to show a toString method
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
/**
* ToString -- demo program to show a toString method.
*/
public class ToString {
int value;
ToString() {
value = 0;
}
ToString(int it) {
value = it;
}
public String toString() {
return "-->" + value + "<--";
}
public static void main(String[] argv) {
ToString s = new ToString(123);
System.out.println("Hello, World of Java");
System.out.println("My object is" + s);
}
}
toString(Object[] array)
/* ------------------------------------------------------------------------
* $Id: ToString.java,v 1.1 2005/07/23 12:56:13 tpv Exp $
* Copyright 2005 Tim Vernum
* ------------------------------------------------------------------------
* 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.
* ------------------------------------------------------------------------
*/
/**
* @version $Revision: 1.1 $
*/
public final class ToString
{
public static String toString(Object[] array)
{
StringBuffer buffer = new StringBuffer();
Class type = array.getClass().getComponentType();
if (type != Object.class)
{
buffer.append(type.getName());
}
if (array.length == 0)
{
buffer.append("[0]");
}
else
{
buffer.append("[");
buffer.append(array.length);
buffer.append("]{");
for (int i = 0; i < array.length; i++)
{
buffer.append(array[i]);
buffer.append(",");
}
buffer.setCharAt(buffer.length() - 1, "}");
}
return buffer.toString();
}
private ToString()
{
// Utility class
}
}
Use a generic toString()
import java.lang.reflect.Field;
public class Main {
public static void main(String args[]) {
System.out.println(new MyClass().toString());
}
}
class MyClass {
String hello = "hi";
int i = 0;
public String toString() {
StringBuilder sb = new StringBuilder();
Class cls = getClass();
Field[] f = cls.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
f[i].setAccessible(true);
try {
sb.append(f[i].getName()+"="+ f[i].get(this)+"\n");
} catch (Exception e) {
e.printStackTrace();
}
}
if (cls.getSuperclass().getSuperclass() != null) {
sb.append("super:"+ super.toString()+"\n");
}
return cls.getName()+"\n" + sb.toString();
}
}