Testing of override of toString()

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

你可能感兴趣的:(apache)