12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

簡単にtoString()を実装する

Last updated at Posted at 2012-03-16

Apache CommonsのCommons LangにToStringBuilderという良いビルダーがあります。

ToStringSample.java
package org.yuichi;

import java.util.Map;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.google.common.collect.Maps;

public class ToStringSample {
    private Map<String, String> map = Maps.newHashMap();

    public ToStringSample() {
        map.put("sample1", "hello");
        map.put("sample2", "world");
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }
}

例えば、このようにtoString()をオーバーライドするとtoString()はこんな感じになります。

org.yuichi.ToStringSample@2352544e[
  map={sample1=hello, sample2=world}
]

出力の形式はreflectionToString()の第2引数に色々渡すことで、変更できます。

12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?