`
kittyjie
  • 浏览: 7132 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

org.apache.commons.lang.builder——ReflectionToStringBuilder类

阅读更多

先看一下常见的用法:

//本示例来自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类进行处理的

分享到:
评论
1 楼 iminto 2010-11-29  
我在本地测试不成功。
http://www.iteye.com/topic/828653

相关推荐

    org.apache.commons.lang jar包下载(commons-lang3-3.1.jar)

    org.apache.commons.lang.builder.ReflectionToStringBuilder$1.class org.apache.commons.lang.builder.ReflectionToStringBuilder.class org.apache.commons.lang.builder.StandardToStringStyle.class org....

    org.apache.commons.lang jar包下载

    org.apache.commons.lang.builder.ReflectionToStringBuilder$1.class org.apache.commons.lang.builder.ReflectionToStringBuilder.class org.apache.commons.lang.builder.StandardToStringStyle.class org....

    org.apache.commons.lang包

    标题中的"org.apache.commons.lang包"指的是该库的主要命名空间,它包含了各种实用工具类,如字符串处理、日期时间操作、类型转换等。 在描述中提到,解压缩Apache Commons Lang资源包后,我们可以获取到几个关键...

    org.apache.commons.lang

    import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder;

    org.apache.commons.lang jar包

    org.apache.commons.lang jar包

    org.apache.commons.lang jar下载

    11. **构建者模式**: Commons Lang 提供了多种Builder类,如 `StringBuilder` 和 `StringBuffer` 的变体,允许更灵活地构建复杂字符串。 12. **枚举枚举**: `EnumSet` 和 `EnumMap` 类提供了针对枚举类型的集合实现...

    org.apache.commons.lang3.StringUtils.jar.rar

    在实际使用 `common-lang3.jar` 时,你可以通过导入 `org.apache.commons.lang3.StringUtils` 类并调用相应的方法来提升字符串处理的效率和代码的可读性。由于这个库经过广泛测试和社区支持,所以它是可靠的,可以在...

    commons-lang.jar

    org.apache.commons.lang.builder.ReflectionToStringBuilder$1.class org.apache.commons.lang.builder.ReflectionToStringBuilder.class org.apache.commons.lang.builder.StandardToStringStyle.class org.apache...

    commons-lang3-3.12.0.zip

    java包。 import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder;

    commons-lang3-3.1 API

    org.apache.commons.lang.builder org.apache.commons.lang.enum org.apache.commons.lang.enums org.apache.commons.lang.exception org.apache.commons.lang.math org.apache.commons.lang.mutable org....

    apache commons-lang简介

    2.1.1.3 org.apache.commons.lang.builder 这个包主要是为了提供对象构建和比较的工具,如ToStringBuilder、HashCodeBuilder和EqualsBuilder,它们帮助开发者生成对象的toString、hashCode和equals方法,避免了重复...

    commons-lang3-3.1.jar_2021.07.zip

    《Apache Commons Lang 3.1:Java编程的强大工具》 Apache Commons Lang 是一个Apache软件基金会提供的Java类库,专门用于处理日常编程任务。这个库包含了大量实用的工具类,极大地扩展了Java的标准库,其中的版本...

    前端-后端java的Util类的工具类

    │ │ │ frame-sourcefiles-org.apache.ibatis.builder.annotation.html │ │ │ frame-sourcefiles-org.apache.ibatis.builder.html │ │ │ frame-sourcefiles-org.apache.ibatis.builder.xml.html │ │ │ ...

    Jakarta Commons笔记

    import org.apache.commons.lang.builder.HashCodeBuilder; public class EqualsHashCodeExample { private int id; private String name; public EqualsHashCodeExample(int id, String name) { this.id = id...

    Commons培训

    2. **org.apache.commons.lang.builder**:该包提供了一系列用于快速生成Java类中常见的方法(如`toString()`、`hashCode()`、`equals()`)的工具类。 3. **org.apache.commons.lang.enum**:这是一个旧的枚举处理包...

    common-lang3.jar

    6. **对象工具**:`org.apache.commons.lang3.builder`提供了对象比较、深拷贝等实用工具,如`EqualsBuilder`和`HashCodeBuilder`用于实现自定义的equals()和hashCode()方法。 7. **异常处理**:`org.apache....

    commons-lang3-3.7

    Apache Commons Lang 3.7 包含多个子包,如 `org.apache.commons.lang3`, `org.apache.commons.lang3.builder`, `org.apache.commons.lang3.text` 等,每个子包都专注于特定的功能领域。例如,`builder` 包提供了...

    commons-lang3-3.1_jar

    这个`commons-lang3-3.1_jar`是Apache Commons Lang项目的一个版本,它提供了大量的类和实用方法,以增强Java语言的功能。在Java开发中,这个库非常常见,能够帮助开发者更高效、便捷地处理各种编程任务。 `...

    commons-lang3-3.0.1.jar

    Apache Commons Lang是Java开发中的一个关键组件,尤其在3.0.1版本中,它提供了大量的实用工具类,大大简化了日常的编程任务。这个名为"commons-lang3-3.0.1.jar"的文件就是Apache Commons Lang 3.0.1的库文件,它是...

Global site tag (gtag.js) - Google Analytics