当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

common toString using reflection

发表于: 2013-05-22   作者:四书五经   来源:转载   浏览:
摘要: core class:   package com.itreply.oschina; import java.lang.reflect.Field; public class GeneralToString { public static String toString(Object obj) { if(obj == null) return &qu

core class:

 

package com.itreply.oschina;

import java.lang.reflect.Field;


public class GeneralToString {
	public static String toString(Object obj) {
		
		if(obj == null) return "null";
		
		StringBuffer sb = new StringBuffer();
		
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		
		sb.append(clazz.getName() + "{");
		try{
			for(Field field :fields){
				field.setAccessible(true);
				sb.append("\n\t" + field.getName() + " = " + field.get(obj));
			}
		} catch(IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sb.append("\n}");
		
		return sb.toString();
	}
}

 

test :

 

package com.itreply.oschina;

public class ClassTest {
	public String publicStringField;
	public static int publicStaticStrField;
	
	private double privateIntField;
	private static float privateStaticFloatField;
	
	protected short protectedShortField;
	protected static long protectedStaticLongField;
	
	public ClassTest(String a, int b, double c, float d, short e, long f) {
		this.publicStringField = a;
		this.publicStaticStrField = b;
		this.privateIntField = c;
		this.privateStaticFloatField =d;
		this.protectedShortField = e;
		this.protectedStaticLongField = f;
	}
	
	public static void main(String[] args) {
		ClassTest c = new ClassTest("hello",10,10.88d,10.9f,(short)11,222222222222222L);
		System.out.println(GeneralToString.toString(c));
		
	}
}

 

 

common toString using reflection

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号