• 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}
  • 相关阅读:
    BZOJ 1202: [HNOI2005]狡猾的商人( 差分约束 )
    BZOJ 1800: [Ahoi2009]fly 飞行棋( 枚举 )
    BZOJ 2006: [NOI2010]超级钢琴( RMQ + 堆 )
    BZOJ 1029: [JSOI2007]建筑抢修( 贪心 )
    FZU 2233 ~APTX4869 贪心+并查集
    FZU2232 炉石传说 最大匹配
    FZU 2237 中位数 主席树 树上k大
    CodeForcesGym 100753B Bounty Hunter II 二分图最小路径覆盖
    NOIP2010关押罪犯 二分+二染色
    POJ2236 Wireless Network 并查集
  • 原文地址:https://www.cnblogs.com/daniell003/p/3311083.html
Copyright © 2020-2023  润新知