先看一下常见的用法:
//本示例来自Jakarta Commons Cookbook
public class PoliticalCandidate {
private String lastName;
private String firstName;
private Date dateOfBirth;
private BigDecimal moneyRaised;
private State homeState;
// get/set methods 省略
public void toString( ) {
ReflectionToStringBuilder.toString( this );
}
}
// Create a State
State va = new State( "VA", "Virginia");
// Create a Birth Date
Calendar calendar = new GregorianCalendar( );
calendar.set( Calendar.YEAR, 1743 );
calendar.set( Calendar.MONTH, Calendar.APRIL );
calendar.set( Calendar.DAY_OF_MONTH, 13 );
Date dob = calendar.getTime( );
BigDecimal moneyRaised = new BigDecimal( 293829292.93 );
// Create a Political Candidate
PoliticalCandidate candidate =
new PoliticalCandidate( "Jefferson", "Thomas", dob, moneyRaised, va );
System.out.println( candidate );
//输出结果
com.discursive.jccook.lang.builders.PoliticalCandidate@187aeca
[lastName=Jefferson,\firstName=Thomas,
dateOfBirth=Sat Apr 13 22:38:42 CST 1743,
moneyRaised=\293829292.930000007152557373046875,
state=\com.discursive.jccook.lang.builders.State@87816d
[abbreviation=VA,name=Virginia]]
这个类其实就是ToStringBuilder类的一个简单实现,真正toString的生成工作全部委托给了ToStringBuilder类去完成。下面看一下这个类的源码,简单的方法就不在说了。
public class ReflectionToStringBuilder extends ToStringBuilder {
public static String toString(Object object) {
return toString(object, null, false, false, null);
}
public static String toString(Object object, ToStringStyle style) {
return toString(object, style, false, false, null);
}
public static String toString(Object object, ToStringStyle style, boolean outputTransients) {
return toString(object, style, outputTransients, false, null);
}
public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) {
return toString(object, style, outputTransients, outputStatics, null);
}
//其他的toString方法都会调用这个toString
public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics,
Class reflectUpToClass) {
//创建ReflectionToStringBuilder示例并调用toString方法
return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics)
.toString();
}
public static String toString(Object object, ToStringStyle style,
boolean outputTransients, Class reflectUpToClass)
{
return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients).toString();
}
//这个方法的作用就是不显示excludeFieldName参数做表示的字段
public static String toStringExclude(Object object, final String excludeFieldName) {
return toStringExclude(object, new String[]{excludeFieldName});
}
public static String toStringExclude(Object object, Collection /*String*/ excludeFieldNames) {
return toStringExclude(object, toNoNullStringArray(excludeFieldNames));
}
//检查数组是否为空,为空的话返回一个String类型的空数组
//EMPTY_STRING_ARRAY = new String[0]
static String[] toNoNullStringArray(Collection collection) {
if (collection == null) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
return toNoNullStringArray(collection.toArray());
}
//去除array数组中的null元素
static String[] toNoNullStringArray(Object[] array) {
ArrayList list = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
Object e = array[i];
if (e != null) {
list.add(e.toString());
}
}
return (String[]) list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
public static String toStringExclude(Object object, String[] excludeFieldNames) {
return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString();
}
//默认toString方法中不显示static字段,transient字段
private boolean appendStatics = false;
private boolean appendTransients = false;
private String[] excludeFieldNames;
private Class upToClass = null;
public ReflectionToStringBuilder(Object object) {
super(object);
}
public ReflectionToStringBuilder(Object object, ToStringStyle style) {
super(object, style);
}
public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
super(object, style, buffer);
}
//这里可以看到ReflectionToStringBuilder的构造函数只是简单的调用了父类的构造函数,并设置一些属性
public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass,
boolean outputTransients) {
super(object, style, buffer);
this.setUpToClass(reflectUpToClass);
this.setAppendTransients(outputTransients);
}
public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass,
boolean outputTransients, boolean outputStatics) {
super(object, style, buffer);
this.setUpToClass(reflectUpToClass);
this.setAppendTransients(outputTransients);
this.setAppendStatics(outputStatics);
}
//这个方法用于判断是否显示内部类,静态字段等
protected boolean accept(Field field) {
/*这里判断如果是内部类的话,就直接返回false,表示不显示。
INNER_CLASS_SEPARATOR_CHAR就是'$',通过反射得到内部类的字段应该有困难,因为每个内部类都持有外部类实例的引用,所以这里只是简单的过滤掉内部类
*/
if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
// Reject field from inner class.
return false;
}
if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
// Reject transient fields.
return false;
}
if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
// Rject static fields.
return false;
}
if (this.getExcludeFieldNames() != null
&& Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {
// Reject fields from the getExcludeFieldNames list.
return false;
}
return true;
}
/*如果clazz是数组类型,则调用reflectionAppendArray方法进行处理。
否则就取得这个clazz表示的类的所有字段,并且把访问属性设置成可访问,这个意思就是说即使字段是private类型,也可以直接取值,而不用调用get方法。
但是注意这句话:If your system is running under a restrictive SecurityManager, you may need to alter your configuration to allow Commons Lang to bypass these security restrictions.
(参见Jakarta Commons Cookbook)
*/
protected void appendFieldsIn(Class clazz) {
if (clazz.isArray()) {
this.reflectionAppendArray(this.getObject());
return;
}
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
if (this.accept(field)) {
try {
// Warning: Field.get(Object) creates wrappers objects
// for primitive types.
Object fieldValue = this.getValue(field);
this.append(fieldName, fieldValue);
} catch (IllegalAccessException ex) {
//this can't happen. Would get a Security exception
// instead
//throw a runtime exception in case the impossible
// happens.
throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
}
}
}
}
public String[] getExcludeFieldNames() {
return this.excludeFieldNames;
}
public Class getUpToClass() {
return this.upToClass;
}
protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {
return field.get(this.getObject());
}
public boolean isAppendStatics() {
return this.appendStatics;
}
public boolean isAppendTransients() {
return this.appendTransients;
}
public ToStringBuilder reflectionAppendArray(Object array) {
this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array);
return this;
}
public void setAppendStatics(boolean appendStatics) {
this.appendStatics = appendStatics;
}
public void setAppendTransients(boolean appendTransients) {
this.appendTransients = appendTransients;
}
public ReflectionToStringBuilder setExcludeFieldNames(String[] excludeFieldNamesParam) {
if (excludeFieldNamesParam == null) {
this.excludeFieldNames = null;
} else {
this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam);
Arrays.sort(this.excludeFieldNames);
}
return this;
}
//设置可以自动查找到的最上层父类。也就是说,到这个类就不在向上查找字段了
public void setUpToClass(Class clazz) {
this.upToClass = clazz;
}
//真正的toString方法
public String toString() {
if (this.getObject() == null) {
//这里调用父类的getStyle方法,格式化字符串的工作由ToStringStyle类来处理
return this.getStyle().getNullText();
}
Class clazz = this.getObject().getClass();
this.appendFieldsIn(clazz);
//这里可以看到会自动附加上父类的字段,可以设置upToClass属性来阻止显示父类的字段
while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) {
clazz = clazz.getSuperclass();
this.appendFieldsIn(clazz);
}
return super.toString();
}
}
通过源码可以看到,真正的工作是交由父类去处理的,而格式化字符串的工作又是由ToStringStyle类进行处理的