Java 反射常用方法 博客分类: JavaJava Web 反射reflectlist转化为map获取私有变量的值访问私有变量
程序员文章站
2024-02-24 12:20:06
...
JAVA 反射常用的方法
作者:1287789687@qq.com
(1)把List 转化为Map
场景:系统中有一个字典类,是一个实体类,如下(省略了getter,setter方法):
/** * Data Dictionary Entity */ @Entity @Table(name = "t_dictionary") public class CommonDictionary implements Cloneable, Serializable { private static final long serialVersionUID = 0x33d260729eadd26eL; /** * 主键id */ private Long id; /** * 组id */ private String groupId; /** * 键<br />不能取值为key,因为key是关键字 */ private String key2; /** * 值 */ private String value; /** * 描述 */ private String description; public CommonDictionary clone() throws CloneNotSupportedException { return (CommonDictionary) super.clone(); }
从数据库中查出的结果是List<CommonDictionary> anticounterfeit,我想把它转化为List,CommonDictionary 中的key2作为map的key,CommonDictionary 中的value作为map的value.
方法如下 :
/*** * * @param list * @param clazz * @param keyProperty : 该成员变量的值作为map的key * @param valueProperty : 该成员变量的值作为map的value * @return */ public static Map<String,Object> parseObjectList(List list,Class clazz,String keyProperty,String valueProperty){ Map<String,Object> map=new HashMap<String, Object>(); for(int i=0;i<list.size();i++){ Object obj=list.get(i); Field keyf =null; Field valuef =null; try { keyf = clazz.getDeclaredField(keyProperty); } catch (NoSuchFieldException e) { keyf= getSpecifiedField(clazz.getSuperclass()/* * may be null if it is * Object . */, keyProperty); // e.printStackTrace(); } try { valuef = clazz.getDeclaredField(valueProperty); } catch (NoSuchFieldException e) { valuef= getSpecifiedField(clazz.getSuperclass()/* * may be null if it is * Object . */, valueProperty); // e.printStackTrace(); } keyf.setAccessible(true); valuef.setAccessible(true); try { map.put((String)keyf.get(obj), valuef.get(obj)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return map; }
依赖的方法:
/*** * Get Specified Field * * @param clazz * @param fieldName * @return */ public static Field getSpecifiedField(Class<?> clazz, String fieldName) { Field f = null; if (ValueWidget.isNullOrEmpty(clazz)) { return null; } try { f = clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { return getSpecifiedField(clazz.getSuperclass()/* * may be null if it is * Object . */, fieldName); // e.printStackTrace(); } return f; }
使用实例:
List<CommonDictionary> anticounterfeit=DictionaryParam.getList(Constant2.DICTIONARY_GROUP_ANTICOUNTERFEIT_CODE); QrSettingsBean qrSettingsBean=new QrSettingsBean(); Map<String,Object>map=ReflectHWUtils.parseObjectList(anticounterfeit, CommonDictionary.class, "key2", "value"); ReflectHWUtils.setObjectValue(qrSettingsBean, map); model.addAttribute("qrSettingsBean", qrSettingsBean);
(2)把Map 转化为java对象,map的key对应对象的成员变量的名称
/*** * 利用反射设置对象的属性值. 注意:属性可以没有setter 方法. * * @param obj * @param params * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void setObjectValue(Object obj, Map<String, Object> params) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { if (ValueWidget.isNullOrEmpty(params)) { return; } Class<?> clazz = obj.getClass(); for (Iterator it = params.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it .next(); String key = entry.getKey(); Object propertyValue = entry.getValue(); if (ValueWidget.isNullOrEmpty(propertyValue)) { continue; } Field name = getSpecifiedField(clazz, key); if (name != null) { name.setAccessible(true); name.set(obj, propertyValue); } } } /*** * Get Specified Field * * @param clazz * @param fieldName * @return */ public static Field getSpecifiedField(Class<?> clazz, String fieldName) { Field f = null; if (ValueWidget.isNullOrEmpty(clazz)) { return null; } try { f = clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { return getSpecifiedField(clazz.getSuperclass()/* * may be null if it is * Object . */, fieldName); // e.printStackTrace(); } return f; }
(3)把对象中 值为空字符串的成员变量 ,将其值改为null
/*** * 把对象中空字符串改为null * @param obj : 要修改的对象:java bean * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void convertEmpty2Null(Object obj) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{ List<Field> fieldsList =getAllFieldList(obj.getClass()); for(int i=0;i<fieldsList.size();i++){ Field f=fieldsList.get(i); Object vObj=getObjectValue(obj,f ); if(f.getType().getName().equals("java.lang.String") && (vObj instanceof String) ){ String str=(String)vObj; if(SystemHWUtil.EMPTY.equals(str)){ // System.out.println(f.getName()); // System.out.println(f.getType().getName()); f.setAccessible(true); f.set(obj, null); } } } }
依赖的方法:
/*** * get all field ,including fields in father/super class * * @param clazz * @return */ public static List<Field> getAllFieldList(Class<?> clazz) { List<Field> fieldsList = new ArrayList<Field>();// return object if (clazz == null) { return null; } Class<?> superClass = clazz.getSuperclass();// father class if (!superClass.getName().equals(Object.class.getName()))/* * java.lang.Object */{ // System.out.println("has father"); fieldsList.addAll(getAllFieldList(superClass));// Recursive } Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; // 排除因实现Serializable 接口而产生的属性serialVersionUID if (!field.getName().equals("serialVersionUID")) { fieldsList.add(field); } } return fieldsList; } /*** * 获取指定对象的属性值 * * @param obj * @param name * :Field * @return * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static Object getObjectValue(Object obj, Field name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { // Field f = getSpecifiedField(obj.getClass(), name.getName()); if (name == null) { System.out.println("[ReflectHWUtils.getObjectValue]" + obj.getClass().getName() + " does not has field " + name); return null; } name.setAccessible(true); return name.get(obj); }
(4)判断两个对象的属性值是否都相等.
/*** * 判断两个对象的属性值是否都相等. * * @param obj1 * @param obj2 * @param exclusiveProperties * : 要过滤的属性 * @return * @throws SecurityException * @throws IllegalArgumentException * @throws NoSuchFieldException * @throws IllegalAccessException */ public static boolean isSamePropertyValue(Object obj1, Object obj2, List<String> exclusiveProperties) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { List<Field> fieldsList = getAllFieldList(obj1.getClass()); for (int i = 0; i < fieldsList.size(); i++) { Field f = fieldsList.get(i); if ((!ValueWidget.isNullOrEmpty(exclusiveProperties)) && exclusiveProperties.contains(f.getName())) {// 过滤掉,不比较 continue; } Object propertyValue1 = getObjectValue(obj1, f); Object propertyValue2 = getObjectValue(obj2, f); System.out.println(f.getName()); if (propertyValue1 == propertyValue2) {// if propertyValue1 is null continue; } if (!isSameBySimpleTypes(propertyValue1, propertyValue2)) { return false; } } return true; } /*** * 比较java 基本类型的值是否相同. * * @param obj1 * : String,Integer,Double,Boolean * @param obj2 * @return */ public static boolean isSameBySimpleTypes(Object obj1, Object obj2) { if (obj1 == obj2) { return true; } if (obj1 instanceof Integer) {// int Integer int1 = (Integer) obj1; Integer int2 = (Integer) obj2; return int1.intValue() == int2.intValue(); } else if (obj1 instanceof Double) {// double Double double1 = (Double) obj1; Double double2 = (Double) obj2; return double1.compareTo(double2) == 0; } else if (obj1 instanceof Boolean) {// double Boolean boolean1 = (Boolean) obj1; Boolean boolean2 = (Boolean) obj2; return boolean1.compareTo(boolean2) == 0; } else if (obj1 instanceof String) { String str1 = (String) obj1; String str2 = (String) obj2; return str1.equals(str2); } else if (obj1 instanceof Timestamp) { Timestamp time1 = (Timestamp) obj1; Timestamp time2 = (Timestamp) obj2; return time1.compareTo(time2) == 0; } else if (obj1 instanceof java.util.Date) { java.util.Date time1 = (java.util.Date) obj1; java.util.Date time2 = (java.util.Date) obj2; return time1.compareTo(time2) == 0; } else if (obj1 instanceof java.sql.Date) { java.sql.Date time1 = (java.sql.Date) obj1; java.sql.Date time2 = (java.sql.Date) obj2; return time1.compareTo(time2) == 0; } return obj1 == obj2; } /*** * 获取指定对象的属性值 * * @param obj * @param name * :Field * @return * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static Object getObjectValue(Object obj, Field name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { // Field f = getSpecifiedField(obj.getClass(), name.getName()); if (name == null) { System.out.println("[ReflectHWUtils.getObjectValue]" + obj.getClass().getName() + " does not has field " + name); return null; } name.setAccessible(true); return name.get(obj); }
设置静态成员变量
/*** * 动态设置com.chanjet.gov.service.API 静态成员变量的值<br> * 注意:应用商店有多台主机进行负载均衡,所以设置完了不一定生效 * @param key * @param val * @return */ @RequestMapping(value = "/setAPIprops", produces = Constant.RESPONSE_CONTENTTYPE_PLAIN_UTF) @ResponseBody public String setAPIproperties(String key,String val) { if(!StringUtil.isNullOrEmpty(key)){ try { Field field= API.class.getDeclaredField(key); field.setAccessible(true); try { field.set(null,val); return val; } catch (IllegalAccessException e) { e.printStackTrace(); return e.getMessage(); } } catch (NoSuchFieldException e) { e.printStackTrace(); return e.getMessage(); } } return "failed"; }
作者:1287789687@qq.com
源码见附件
上一篇: MySQL连接及基本信息查看命令汇总
下一篇: 脚本管理框架JSI2.5预览版发布