`
tanglei198577
  • 浏览: 57857 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

Testing of override of toString()

    博客分类:
  • java
阅读更多

At fisrt,thanks for the tips of Xia,I just  run the situation he described.

        When we want to print the properties of POJO, we can override the function toString() for conveninence , here is my testing code:

        Created a object Student:

       

package mysrc;
import java.io.Serializable;

import org.apache.commons.lang.builder.ToStringBuilder;

public class Student implements Serializable{

	int id;
	String name;
	//construct
	Student (){		
	}
	
	Student(int id,String name){
		this.id = id;
		this.name = name;
	}
	
	//override
	public  String toString(){		
		return ToStringBuilder.reflectionToString(this);
	}
	
	//the different way to implement this function
	public String toStr(){
		return new ToStringBuilder(this).append("id",id).append("name",name).toString();
	}

}

    Then test these two methods:

   

package mysrc;

public class ToStringTest {	
	public static void main(String args[]){		
		Student stu = new Student(10086,"tanglei");		
		System.out.println(stu.toString());
		System.out.println(stu.toStr());
	}
}

   Then the result is :

          mysrc.Student@a62fc3[id=10086,name=tanglei]
          mysrc.Student@a62fc3[id=10086,name=tanglei]

   Ok,that's all

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics