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);
}
public void change(String name, int orcNumber) {
set(name);
}
public String toString() {
return "Orc" + orcNumber + ":" + String();
}
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.());
}
}
}
在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 flect.Field;
public class BaseBean {
java的tostring方法public String toString() {
StringBuffer sb = new StringBuffer();
try {
Class t = Class();
Field[] fields = t.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
sb.append("{");
sb.Name());
sb.append(":");
if (Type() == Integer.class) {
sb.Int(this));
} else if (Type() == Long.class) {
sb.Long(this));
} else if (Type() == Boolean.class) {
sb.Boolean(this));
} else if (Type() == char.class) {
sb.Char(this));
} else if (Type() == Double.class) { sb.Double(this));
} else if (Type() == Float.class) { sb.Float(this));
} else
sb.(this));
sb.append("}");
}
} catch (Exception e) {
e.printStackTrace();
}
String();
}
}
测试类
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.String());
}
}
结果
{id:9}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论