java toString()用法

來源:互聯網
上載者:User
 
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@11b86e7sample.Orc@11b86e7如果去掉注釋,即加入2個toString()方法後,得到結果:Orc12:I'm a Villain and my name is LimburgerOrc19:I'm a Villain and my name is Bob2.在容器類中使用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 #0This is Hamster #1This is Hamster #23.一個實現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}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.