日期:2014-05-20  浏览次数:20836 次

谁知道ToStringBuilder的作用是什么呢
如题

------解决方案--------------------
[code=Java][/code]public class ToStringBuilder
extends Object
Assists 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, 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.
------解决方案--------------------
lz参考一下这个:

http://commons.apache.org/lang/api-release/org/apache/commons/lang/builder/ToStringBuilder.html
------解决方案--------------------
这是apache开源基金会的 commons-lang 项目下的一个类。

我正好用过,功能就是在自己定义一个类的toString 方法时,方便的格式化类的属性。

public class User {
private Integer id;
private String name;
private String password;

// ...

public String toString() {
return new ToStringBuilder(this, ToStringStyle.SIMPLE)
.append(id)
.append(name)
.append(password);
}

public static void main(String[] args) {
System.out.println(user);
}
}

如果运行上面的main方法的话,user的属性就可以漂亮的被打印出来了。
------解决方案--------------------
探讨

英语不好,看不懂,不能给分