应用反射写的tostring方法

应用反射写的tostring方法

应用反射写的tostring方法,方便以后查询

代码

package com.chzhao.reflecttest;

import java.lang.reflect.Field;
import java.util.List;

public class ToStringToolkit {
	@SuppressWarnings("rawtypes")
	public static <T> String toStringGeneric(T t) {
		StringBuilder sb = new StringBuilder();
		Class clazz = (Class) t.getClass();
		Field[] fs = clazz.getDeclaredFields();
		for (int i = 0; i < fs.length; i++) {
			Field f = fs[i];
			f.setAccessible(true);
			sb.append("\t");
			sb.append(f.getName());
			sb.append(":");
			try {
				sb.append(f.get(t).toString());
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		sb.append("\n");
		return sb.toString();
	}

	public static <T> String toStringList(List<T> list) {
		StringBuilder sb = new StringBuilder();
		for (T t : list) {
			sb.append(toStringGeneric(t));
		}
		return sb.toString();
	}
}

用法

package com.chzhao.reflecttest;

public class Model {

	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;
	}
}

package com.chzhao.reflecttest;

public class App {
	public static void main(String[] args) {
		Model m = new Model();
		m.setAge(100);
		m.setName("找");
		System.out.println(ToStringToolkit.toStringGeneric(m));
	}
}

输出

	name:找	age:100
posted @ 2015-01-27 17:37  wardensky  阅读(191)  评论(0编辑  收藏  举报