反射常用的方法
(1)把List 转化为Map
场景:系统中有一个字典类,是一个实体类,如下(省略了getter,setter方法):
-
-
-
- @Entity
- @Table(name = "t_dictionary")
- public class CommonDictionary implements Cloneable, Serializable {
-
- private static final long serialVersionUID = 0x33d260729eadd26eL;
-
-
-
-
- private Long id;
-
-
-
- private String groupId;
-
-
-
- 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.
方法如下 :
-
-
-
-
-
-
-
-
- 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()
-
-
- , keyProperty);
-
- }
- try {
- valuef = clazz.getDeclaredField(valueProperty);
- } catch (NoSuchFieldException e) {
- valuef= getSpecifiedField(clazz.getSuperclass()
-
-
- , valueProperty);
-
- }
- 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;
- }
依赖的方法:
-
-
-
-
-
-
-
- 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()
-
-
- , fieldName);
-
- }
- 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对应对象的成员变量的名称
-
-
-
-
-
-
-
-
-
-
- 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);
- }
- }
-
- }
-
-
-
-
-
-
-
- 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()
-
-
- , fieldName);
-
- }
- return f;
- }
(3)把对象中 值为空字符串的成员变量 ,将其值改为null
-
-
-
-
-
-
-
-
- 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)){
-
-
- f.setAccessible(true);
- f.set(obj, null);
- }
- }
- }
- }
依赖的方法:
-
-
-
-
-
-
- public static List<Field> getAllFieldList(Class<?> clazz) {
- List<Field> fieldsList = new ArrayList<Field>();
- if (clazz == null) {
- return null;
- }
-
- Class<?> superClass = clazz.getSuperclass();
- if (!superClass.getName().equals(Object.class.getName()))
-
- {
-
-
- fieldsList.addAll(getAllFieldList(superClass));
- }
- Field[] fields = clazz.getDeclaredFields();
- for (int i = 0; i < fields.length; i++) {
- Field field = fields[i];
-
- if (!field.getName().equals("serialVersionUID")) {
- fieldsList.add(field);
- }
- }
- return fieldsList;
- }
-
-
-
-
-
-
-
-
-
-
-
-
- public static Object getObjectValue(Object obj, Field name)
- throws SecurityException, NoSuchFieldException,
- IllegalArgumentException, IllegalAccessException {
-
-
- 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)判断两个对象的属性值是否都相等.
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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) {
- continue;
- }
- if (!isSameBySimpleTypes(propertyValue1, propertyValue2)) {
- return false;
- }
- }
- return true;
- }
-
-
-
-
-
-
-
-
-
- public static boolean isSameBySimpleTypes(Object obj1, Object obj2) {
- if (obj1 == obj2) {
- return true;
- }
- if (obj1 instanceof Integer) {
- Integer int1 = (Integer) obj1;
- Integer int2 = (Integer) obj2;
- return int1.intValue() == int2.intValue();
- } else if (obj1 instanceof Double) {
- Double double1 = (Double) obj1;
- Double double2 = (Double) obj2;
- return double1.compareTo(double2) == 0;
- } else if (obj1 instanceof Boolean) {
- 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;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static Object getObjectValue(Object obj, Field name)
- throws SecurityException, NoSuchFieldException,
- IllegalArgumentException, IllegalAccessException {
-
-
- 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);
- }