1. 介绍

很多场景下我们都需要做序列化传输。把String对象作为序列化传输的对象也十分常见。把对象转化成String对象可以通过覆盖toString方法。本文主要介绍如何使用ToStringBuilder来将对象按照我们约定的格式来转化成String对象。

2. 代码

首先在POM中引入依赖:

            <dependency>
                <groupId>commons-lang</groupId>
                <artifactId>commons-lang</artifactId>
                <version>2.6</version>
            </dependency>
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * @author Wan Kaiming on 2016/8/15
 * @version 1.0
 */
public class ToStringBuilderTest {

    public static void main(String[] args) {
        User u = new User();
        u.setAge(19);
        u.setName("Kami");


        //对象及其属性一行显示
        System.out.println(ToStringBuilder.reflectionToString(u));
        System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.DEFAULT_STYLE));
        //属性换行显示
        System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.MULTI_LINE_STYLE));
        //不显示属性名,只显示属性值,在同一行显示
        System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.NO_FIELD_NAMES_STYLE));
        //对象名称简写
        System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.SHORT_PREFIX_STYLE));
        //只显示属性
        System.out.println(ToStringBuilder.reflectionToString(u, ToStringStyle.SIMPLE_STYLE));
    }


}


class User {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}