Java之toString()方法详解

来源:互联网 发布:spring面向切面编程 编辑:程序博客网 时间:2024/06/06 04:48

Java之toString()方法详解

Java中 toString()方法在Object类中和Intent类中都有定义,作用类似,但显示形式有点区别

一、Object类中toString()方法

toString() 是java.lang.Object类的方法
定义:public String toString()

源代码:

 public String toString() {

        return getClass().getName() + "@" + Integer.toHexString(hashCode());

    }

 

public String toString ()

添加于 API 级别 1

Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:

   getClass().getName() + '@' + Integer.toHexString(hashCode())

See Writing a useful toString method if you intend implementing your own toString method.

返回值
  • a printable representation of this object.

返回该对象的字符串表示。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法

Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于:

getClass().getName() + '@' + Integer.toHexString(hashCode())

  返回:该对象的字符串表示形式。

  说明:

输出对象时一般会自动调用toString( )方法把对象转换为字符串。例如System.out.println(obj),括号里面的 “obj”如果不是String类型的话,而是对象时,就自动调用obj.toString()方法。当然也可以重载toString( )方法,指定返回的形式。

public class Text01{       public static class A       {              public String toString()              {                     return "this is A";//指定返回的形式              }       }       public static void main(String[] args)       {              A obj = new A();              System.out.println(obj);//等同于 System.out.println(obj.toString( ));        }}

输出:this is A

如果把 toString()注释掉,那么得到:Demo@ed5ba6,其中getClass().getName()返回值为Demo@后面对应的是此对象哈希码的无符号十六进制表示形式。

二、Intent类中toString()方法

    public String toString() {        StringBuilder b = new StringBuilder(128);        b.append("Intent { ");        toShortString(b, true, true, true, false);        b.append(" }");        return b.toString();//调用Object类中toString方法,实质上,我们可以<span style="font-family:宋体;">通过</span><span style="color: rgb(51, 153, 102);">子类都重写此方法,根据自己的需要指定返回形式</span>    }


0 0