1.1 org.apache.commons.lang.builder.ToStringBuilder

介绍:

属于Apache Common Lang项目下的类,作用是实现Object中的toString方法

如何使用(how to use

Reference to Javadoc

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, use appendSuper(java.lang.String). To append the toString from an object that is delegated to (or any other object), use appendToString(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, uses AccessibleObject.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 the ToStringStyle passed into the constructor.

Constructor methods:

ToStringBuilder(Object object)

    Constructs a builder for the specified object using the default output style.

ToStringBuilder(Object object, ToStringStyle style)
    Constructs a builder for the specified object using the a defined output style.

ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer)

    Constructs a builder for the specified object.

 

1.2 org.apache.commons.lang.builder.ToStringStyle

介绍:

属于Apache Common Lang项目下的类,作用是Controls String formatting for ToStringBuilder. The main public interface is always via ToStringBuilder.

 

如何使用(how to use:

public abstract class ToStringStyle

extends Object

implements Serializable

These classes are intended to be used as Singletons. There is no need to instantiate a new style each time. A program will generally use one of the predefined constants on this class. Alternatively, the StandardToStringStyle class can be used to set the individual settings. Thus most styles can be achieved without subclassing. --->抽象类的单例模式,使用类中的静态成员变量

If required, a subclass can override as many or as few of the methods as it requires. Each object type (from boolean to long to Object to int[]) has its own methods to output it. Most have two versions, detail and summary.

For example, the detail version of the array based methods will output the whole array, whereas the summary method will just output the array length.

If you want to format the output of certain objects, such as dates, you must create a subclass and override a method.

 public class MyStyle extends ToStringStyle {

   protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {

     if (value instanceof Date) {

       value = new SimpleDateFormat("yyyy-MM-dd").format(value);

     }

     buffer.append(value);

   }

 }

ToStringStyle类的设计:

ToStringStyle类代表的是java对象在toString时,形成String的格式。

ToStringStyle类是abstract的,所以不能被实例化。

客户端代码在使用ToStringStyle类时,是采用单例的方式,为什么说采用单例的方式呢?因为ToStringStyle类利用了静态成员变量一个类中只有一份实例这个特性,同时ToStringStyle类本身无法实例化,这样可以保证ToStringStyle类中的静态成员变量永远只有一份。然后ToStringStyle类里预先定义了5public static finalToStringStyle成员变量,分别代表着5String的格式。ToStringStyle类的这种设计,保证程序运行时预先定义的5public static finalToStringStyle成员变量只有一份。

这种设计方法是单例模式的一个变种吧。

DEFAULT_STYLE

public static final ToStringStyle DEFAULT_STYLE

The default toString style. Using the Using the Person example from ToStringBuilder, the output would look like this: 

 Person@182f0db[name=John Doe,age=33,smoker=false]

MULTI_LINE_STYLE

public static final ToStringStyle MULTI_LINE_STYLE

The multi line toString style. Using the Using the Person example from ToStringBuilder, the output would look like this: 

 Person@182f0db[

   name=John Doe

   age=33

   smoker=false

 ]

NO_FIELD_NAMES_STYLE

public static final ToStringStyle NO_FIELD_NAMES_STYLE

The no field names toString style. Using the Using the Person example from ToStringBuilder, the output would look like this: 

 Person@182f0db[John Doe,33,false]

SHORT_PREFIX_STYLE

public static final ToStringStyle SHORT_PREFIX_STYLE

The short prefix toString style. Using the Person example from ToStringBuilder, the output would look like this: 

 Person[name=John Doe,age=33,smoker=false]

 

Since:

2.1

SIMPLE_STYLE

public static final ToStringStyle SIMPLE_STYLE

The simple toString style. Using the Using the Person example from ToStringBuilder, the output would look like this: 

 John Doe,33,false

这五个静态成员变量在ToStringStyle类中的定义如下:

public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle(); //代表了default format

public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle(); //代表了multiline format

。。。

它们都实现了ToStringStyle类,ToStringStyle类文件的后面有这些类的声明:

private static final class DefaultToStringStyle extends ToStringStyle {

。。。

}

。。。

把这些具体类型也写在ToStringStyle类文件里面,因为它们一起向外提供功能,这样可以减少java类文件的数量,方便维护。

DefaultToStringStyle,MultiLineToStringStyle,NoFieldNameToStringStyle。。这些类的具体实现

在构造方法中设置ToStringStyle类中的成员变量,这些成员变量是最后形成的String中的元素或一些boolean类型的标识符,用来控制输出。

例如:

private static final class NoFieldNameToStringStyle extends ToStringStyle {

        NoFieldNameToStringStyle() {

            super();

            this.setUseFieldNames(false); //ToStringStyle类中的成员变量,boolean类型的标识符,用来控制是否显示field的名字。

        }

。。。。

 

这五种ToStringStylejdk内置的,格式已经定死。但是用户如果想自己定义格式怎么办呢?Jdk已经考虑到了这点。

 

1.3 org.apache.commons.lang.builder.StandardToStringStyle

java.lang.Object

  org.apache.commons.lang.builder.ToStringStyle

      org.apache.commons.lang.builder.StandardToStringStyle

 

介绍:

Works with ToStringBuilder to create a toString.

This class is intended to be used as a singleton. There is no need to instantiate a new style each time. Simply instantiate the class once, customize the values as required, and store the result in a public static final variable for the rest of the program to access.

如何使用(how to use:

 

 public class Person {

   String name;

   int age;

   boolean smoker;

   ...

   public String toString() {

     ToStringStyle myStyle = new StandardToStringStyle();

 myStyle.setShortClassName(true);

 

     return new ToStringBuilder(this, myStyle ).

       append("name", name).

       append("age", age).

       append("smoker", smoker).

       toString();

   }

 }