java利用反射技术遍历某个对象的属性及属性值

来源:互联网 发布:怎样进入淘宝后台管理 编辑:程序博客网 时间:2024/06/05 01:56

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<String,String> map=readClassAttr(tb);
   System.out.println(map.get("keys"));
   System.out.println(map.get("values"));
  } catch (Exception e) {
   e.printStackTrace();
  }
 
}

//用来遍历对象属性和属性值
public static Map<String,String> 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<String,String> maps=new HashMap<String, String>();
  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;
// }
}

原创粉丝点击