欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Testing of override of toString()

程序员文章站 2022-04-08 16:32:32
...

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 :

          [email protected][id=10086,name=tanglei]
          [email protected][id=10086,name=tanglei]

   Ok,that's all

相关标签: Apache