java 中toString()方法详解

1.toString()方法
Object类具有一个toString()方法,你创建的每个类都会继承该方法。它返回对象的一个String表示,并且对于调试非常有帮助。然而对于默认的toString()方法往往不能满足需求,需要覆盖这个方法。
toString()方法将对象转换为字符串。看以下代码:
package sample;
 
class Villain {
    private String name;
 
    protected void set(String nm) {
       name = nm;
    }
 
    public Villain(String name) {
       this.name = name;
    }
 
    public String toString() {
       return "I'm a Villain and my name is " + name;
    }
}
 
public class Orc extends Villain {
    private int orcNumber;
 
    public Orc(String name, int orcNumber) {
       super(name);
       this.orcNumber = orcNumber;
    }
 
    public void change(String name, int orcNumber) {
       set(name);
       this.orcNumber = orcNumber;
    }
 
    public String toString() {
       return "Orc" + orcNumber + ":" + super.toString();
    }
 
    public static void main(String[] args) {
       Orc orc = new Orc("Limburger", 12);
       System.out.println(orc);
       orc.change("Bob", 19);
       System.out.println(orc);
    }
}
 
结果:
sample.Orc@11b86e7
sample.Orc@11b86e7
如果去掉注释,即加入2个toString()方法后,得到
结果:
Orc12:I'm a Villain and my name is Limburger
Orc19:I'm a Villain and my name is Bob
 
2.在容器类中使用toString()
编写一个工具类,用于在控制台输出Iterator。
import java.util.Iterator;
 
public class Printer {
    static void printAll(Iterator e){
       while(e.hasNext()){
           System.out.println(e.next());
       }
    }
}
在Hamster类中重写父类的toString()方法。
public class Hamster {
    private int hamsterNumber;
    public Hamster(int hamsterNumber){
       this.hamsterNumber=hamsterNumber;
    }
 
    public String toString(){
       return "This is Hamster #"+hamsterNumber;
    }
}
在HamsterMaze类中使用容器类加载Hamster类对象并输出结果。
import java.util.ArrayList;
import java.util.List;
 
public class HamsterMaze {
    @SuppressWarnings("unchecked")
    public static void main(String[] args){
       List list=new ArrayList();
       for(int i=0;i<3;i++)
           list.add(new Hamster(i));
       Printer.printAll(list.iterator());
    }
}
结果:
This is Hamster #0
This is Hamster #1
This is Hamster #2
 
3.一个实现toString()的通用的Bean
在作一个项目时发现,许多bean需要实现toString()方法,就实现一个通用的bean,然后通过其他继承即可。
import java.lang.reflect.Field;
 
public class BaseBean {
  
    public String toString() {
       StringBuffer sb = new StringBuffer();
       try {
           Class t = this.getClass();
           Field[] fields = t.getDeclaredFields();
           for (int i = 0; i < fields.length; i++) {
              Field field = fields[i];
              field.setAccessible(true);
              sb.append("{");
              sb.append(field.getName());
              sb.append(":");
              if (field.getType() == Integer.class) {
                  sb.append(field.getInt(this));
              } else if (field.getType() == Long.class) {
                  sb.append(field.getLong(this));
              } else if (field.getType() == Boolean.class) {
                  sb.append(field.getBoolean(this));
              } else if (field.getType() == char.class) {
                  sb.append(field.getChar(this));
              } else if (field.getType() == Double.class) {
                  sb.append(field.getDouble(this));
              } else if (field.getType() == Float.class) {
                  sb.append(field.getFloat(this));
              } else
                  sb.append(field.get(this));
              sb.append("}");
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return sb.toString();
    }
}
 
测试类
public class TestBean extends BaseBean {
 
    private int id;
 
    public int getId() {
       return id;
    }
 
    public void setId(int id) {
       this.id = id;
    }
 
    public static void main(String[] args) {
       TestBean testBean = new TestBean();
       testBean.setId(9);
       System.out.println(testBean.toString());
    }
}
结果
{id:9}
posted @ 2013-09-09 22:07  daniell2012  阅读(27083)  评论(0编辑  收藏  举报