使用ToStringBuilder重写toString方法

--
package com.osc.demo;

import java.util.List;

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

public class Teacher {
	private String name;
	private int age;
	private List<Student> student;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public List<Student> getStudent() {
		return student;
	}

	public void setStudent(List<Student> student) {
		this.student = student;
	}

	@Override
	public String toString() {
		//return new ToStringBuilder(this,ToStringStyle.SHORT_PREFIX_STYLE).append("name", this.name).append("age",this.age).append("student",this.student).toString();
		return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE);
	}
}
--
package com.osc.demo;

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

public class Student {
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		//return new ToStringBuilder(this,ToStringStyle.SHORT_PREFIX_STYLE).append("name", this.name).append("age",this.age).toString();
		return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE);
	}
}
--
package com.osc.demo;

import java.util.ArrayList;
import java.util.List;

public class Test {
	public static void main(String[] args) {
		Student studentOne = new Student();
		studentOne.setName("张柏芝");
		studentOne.setAge(34);
		List<Student> studentList = new ArrayList<Student>();
		studentList.add(studentOne);
		Teacher teacher = new Teacher();
		teacher.setName("陈冠希");
		teacher.setAge(33);
		teacher.setStudent(studentList);
		System.out.println(teacher);
	}
}

-- 

Teacher[name=陈冠希,age=33,student=[Student[name=张柏芝,age=34]]]

你可能感兴趣的:(使用ToStringBuilder重写toString方法)