package com.bean;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Test3 { public static void main(String[] args) { TestBean tb=new TestBean(); tb.setA("2012-8-5"); tb.setB("bbb"); tb.setC("ccc"); try { Map map=readClassAttr(tb); System.out.println(map.get("keys")); System.out.println(map.get("values")); } catch (Exception e) { e.printStackTrace(); } } //用来遍历对象属性和属性值 public static Map readClassAttr(TestBean tb) throws Exception{ Field[] fields=tb.getClass().getDeclaredFields(); String keyList=""; String valueList=""; for(Field field:fields){ field.setAccessible(true); //实体属性为private,此处必须写上 if(field.get(tb)!=null&&!"".equals(field.get(tb).toString())){ keyList+=","+field.getName(); if("a".equals(field.getName())){ valueList+=","+"特殊格式哦"; }else{ valueList+=","+field.get(tb); } ///System.out.println(field.getName()+" "+field.get(tb).toString()); } } Map maps=new HashMap(); maps.put("keys", keyList); maps.put("values",valueList); return maps; } // public static String readClassAttr(TestBean tb) throws Exception{ // Field[] fields=tb.getClass().getDeclaredFields(); // for(Field field:fields){ // field.setAccessible(true); // System.out.println(field.getName()+" "); // PropertyDescriptor pd = new PropertyDescriptor(field.getName(),TestBean.class); // Method getMethod = pd.getReadMethod();//获得get方法 // Object o = getMethod.invoke(tb);//执行get方法返回一个Object // System.out.println(o); // // } // return null; // } }