package com.lion.util;import java.lang.reflect.Field;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;/** * * @author liyongyao * */public class GetClassInfo {    /**     * 获得属性名     *     * @param object     * @return     */    public static ArrayList
ComponentsName(Object object) { Field[] fields = object.getClass().getDeclaredFields(); ArrayList
filedName = new ArrayList
(); for (int i = 0; i < fields.length; i++) { try { String varName = fields[i].getName(); boolean accessFlag = fields[i].isAccessible(); fields[i].setAccessible(true); filedName.add(varName); fields[i].setAccessible(accessFlag); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } return filedName; } /** * 获取键值对 * * @param object * @return */ public static Map
ComponentsNameAndValue(Object object) { Field[] fields = object.getClass().getDeclaredFields(); Map
nameAndValue = new HashMap
(); ArrayList
filedName = new ArrayList
(); ArrayList
filedValue = new ArrayList(); for (int i = 0; i < fields.length; i++) { try { boolean accessFlag = fields[i].isAccessible(); fields[i].setAccessible(true); String varName = fields[i].getName(); Object varValue = fields[i].get(object); filedName.add(varName); filedValue.add(varValue); fields[i].setAccessible(accessFlag); } catch (Exception e) { e.printStackTrace(); } } nameAndValue.put("value", filedValue); nameAndValue.put("key", filedName); return nameAndValue; } /** * 获取键值对打印到控制台 * * @param object * @return */ public static void printClassInfo(Object object) { Field[] fields = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { boolean accessFlag = fields[i].isAccessible(); fields[i].setAccessible(true); String varName = fields[i].getName(); Object varValue = fields[i].get(object); System.out.println(varName + "=" + varValue); fields[i].setAccessible(accessFlag); } catch (Exception e) { e.printStackTrace(); } } } /** * 根据属性名称查找对象中的相应值 * * @param name * 属性名 * @param object * 要查找的对象 * @return Object 返回属性对应的值 */ public static Object getValueByName(String name, Object object) { try { Field f = object.getClass().getDeclaredField(name); boolean accessFlag = f.isAccessible(); f.setAccessible(true); Object o = f.get(object); f.setAccessible(accessFlag); return o; } catch (Exception e) { e.printStackTrace(); } return null; } public static Object setValueByName(String name, Object value, Object object) { try { Field f = object.getClass().getDeclaredField(name); boolean accessFlag = f.isAccessible();// 获得原始权限 f.setAccessible(true);// 权限设置为可访问 f.set(object, value); f.setAccessible(accessFlag);// 还原权限 return object; } catch (Exception e) { e.printStackTrace(); } return null; }}