java获取Object属性类型、属性名称、属性值
1 package com.jf.ftp; 2 3 import java.lang.reflect.Field; 4 import java.lang.reflect.Method; 5 import java.util.ArrayList; 6 import java.util.HashMap; 7 import java.util.List; 8 import java.util.Map; 9 10 import org.apache.log4j.Logger; 11 12 public class ObjectUtil { 13 14 private static Logger log = Logger.getLogger(NewFtpUtil.class); 15 16 /** 17 * 根据属性名获取属性值 18 * */ 19 private Object getFieldValueByName(String fieldName, Object o) { 20 try { 21 String firstLetter = fieldName.substring(0, 1).toUpperCase(); 22 String getter = "get" + firstLetter + fieldName.substring(1); 23 Method method = o.getClass().getMethod(getter, new Class[] {}); 24 Object value = method.invoke(o, new Object[] {}); 25 return value; 26 } catch (Exception e) { 27 log.error(e.getMessage(), e); 28 return null; 29 } 30 } 31 32 /** 33 * 获取属性名数组 34 * */ 35 private String[] getFiledName(Object o) { 36 Field[] fields = o.getClass().getDeclaredFields(); 37 String[] fieldNames = new String[fields.length]; 38 for (int i = 0; i < fields.length; i++) { 39 System.out.println(fields[i].getType()); 40 fieldNames[i] = fields[i].getName(); 41 } 42 return fieldNames; 43 } 44 45 /** 46 * 获取属性类型(type),属性名(name),属性值(value)的map组成的list 47 * */ 48 private List getFiledsInfo(Object o) { 49 Field[] fields = o.getClass().getDeclaredFields(); 50 String[] fieldNames = new String[fields.length]; 51 List list = new ArrayList(); 52 Map infoMap = null; 53 for (int i = 0; i < fields.length; i++) { 54 infoMap = new HashMap(); 55 infoMap.put("type", fields[i].getType().toString()); 56 infoMap.put("name", fields[i].getName()); 57 infoMap.put("value", getFieldValueByName(fields[i].getName(), o)); 58 list.add(infoMap); 59 } 60 return list; 61 } 62 63 /** 64 * 获取对象的所有属性值,返回一个对象数组 65 * */ 66 public Object[] getFiledValues(Object o) { 67 String[] fieldNames = this.getFiledName(o); 68 Object[] value = new Object[fieldNames.length]; 69 for (int i = 0; i < fieldNames.length; i++) { 70 value[i] = this.getFieldValueByName(fieldNames[i], o); 71 } 72 return value; 73 } 74 }