JavaBeans with ToStringBuilder

DAOを利用しているとEmployeeクラスやProductクラスといったJavaBeansも増えてきます。デバッグやUnitTestの際にこれらのクラスのプロパティを整形して出力したい場面がよくありますが、いちいちtoStringメソッドを書いていくのは面倒ですよね。

そこでJakarta Commons Langに含まれるToStringBuilderの出番です。JavaBeansの中で以下のようにtoStringメソッドを定義してみましょう。

public class Product {
    private Long id = null;
    private String name = null;
    private Integer price = null;
    private Boolean inStock = null;
    private Float weight = null;

// getter, setterは省略

public String toString() {
    return new ToStringBuilder(this).
        append("id", id).
        append("name", name).
        append("price", price).
        append("inStock", inStock).
        append("weight", weight).
        toString();
}

}

このJavaBeansを以下のように利用すると、

public class ProductDemo {
    public static void main(String[] args) {
        Product product = new Product();
        product.setId(new Long(1));
        product.setName("Foo");
        product.setPrice(new Integer(1980));
        product.setInStock(Boolean.valueOf(true));
        product.setWeight(null);

    System.out.println(product);
}

}

次のように出力されます。

$ java ProductDemo
src.Product@1ad086a[id=1,name=Foo,price=1980,inStock=true,weight=<null>]

このままでも結構便利なのですが、プロパティが多くなってくると結果が見づらくなってくるので、ProductクラスのtoStringメソッドを以下のように変更します。

public String toString() {
    return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).
        append("id", id).
        append("name", name).
        append("price", price).
        append("inStock", inStock).
        append("weight", weight).
        toString();
}

ToStringBuilderは出力のフォーマットをToStringStyleオブジェクトによって自由に変更することができるため、ToStringStyleクラスのインナークラスとして標準で用意されているToStringStyle.MultiLineToStringStyleのインスタンスを指定しています。

結果は以下の通り。

$ java ProductDemo
src.Product@1ad086a[
  id=1
  name=Foo
  price=1980
  inStock=true
  weight=<null>
]

使用可能なタグ <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>