ToStringBuilder (Commons Lang 2.4 API)
org.apache.commons.lang.builder
Class ToStringBuilder
java.lang.Object org.apache.commons.lang.builder.ToStringBuilderDirect Known Subclasses:
- ReflectionToStringBuilder
public class
ToStringBuilder extends java.lang.ObjectAssists in implementing
Object.toString()
methods.This class enables a good and consistent
toString()
to be built for any
class or object. This class aims to simplify the process by:
- allowing field names
- handling all types consistently
- handling nulls consistently
- outputting arrays and multi-dimensional arrays
- enabling the detail level to be controlled for Objects and Collections
- handling class hierarchies
To use this class write code as follows:
public class Person { String name; int age; boolean smoker; ... public String toString() { return new ToStringBuilder(this). append("name", name). append("age", age). append("smoker", smoker). toString(); } }This will produce a toString of the format:
Person@7f54[name=Stephen,age=29,smoker=false]
To add the superclass
toString
, useappendSuper(java.lang.String)
.
To append thetoString
from an object that is delegated
to (or any other object), useappendToString(java.lang.String)
.Alternatively, there is a method that uses reflection to determine
the fields to test. Because these fields are usually private, the method,reflectionToString
, usesAccessibleObject.setAccessible
to
change the visibility of the fields. This will fail under a security manager,
unless the appropriate permissions are set up correctly. It is also
slower than testing explicitly.A typical invocation for this method would look like:
public String toString() { return ToStringBuilder.reflectionToString(this); }You can also use the builder to debug 3rd party objects:
System.out.println("An object: " + ToStringBuilder.reflectionToString(anObject));The exact format of the
toString
is determined by
theToStringStyle
passed into the constructor.
Since:
- 1.0
Version:
- $Id: ToStringBuilder.java 492354 2007-01-03 23:48:10Z scolebourne $
Author:
- Stephen Colebourne, Gary Gregory, Pete Gieser
转载于:https://www.cnblogs.com/lexus/archive/2012/06/26/2563149.html
今天的文章Class ToStringBuilder分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/7506.html