直接赋值会报错
Method threw 'java.lang.UnsupportedOperationException' exception.
给没有set方法的类如下赋值
public static void setFieldValue(Object obj, String fieldName, Object val) { if (isEmpty(obj) || isEmpty(fieldName)) return; Class superClass=obj.getClass(); List<Field> clazzs=new ArrayList<>(); while(superClass!=null){ clazzs.addAll(Arrays.asList(superClass.getDeclaredFields())); superClass=superClass.getSuperclass(); } try { for (Field f : clazzs) { if (f.getName().equals(fieldName)) { f.setAccessible(true); f.set(obj, val); return; } } } catch (IllegalArgumentException e) { logger.error("error", e); } catch (IllegalAccessException e) { logger.error("error", e); } } public static boolean isEmpty(String...strings){ if(strings==null||strings.length==0) return true; for(String s : strings){ if(!isEmpty(s)) return false; } return true; } public static boolean isEmpty(String str) { return str == null || str.trim().length() == 0; } public static boolean isEmpty(Collection<?> col) { return col == null || col.size() == 0; } public static boolean isEmpty(Map<?, ?> map) { return map == null || map.size() == 0; } public static boolean isEmpty(Object[] obj) { return obj == null || obj.length == 0; } public static boolean isEmpty(Object obj) { if (obj == null) return true; else if (obj instanceof String) { String str = (String) obj; return str.trim().length() == 0; } else if (obj instanceof Map) { Map<?, ?> map = (Map<?, ?>) obj; return map.size() == 0; } else if (obj instanceof Collection) { Collection<?> col = (Collection<?>) obj; return col.size() == 0; } else if (obj instanceof Dictionary) { Dictionary<?, ?> dic = (Dictionary<?, ?>) obj; return dic.size() == 0; } else if (obj instanceof Object[]) { Object[] objs = (Object[]) obj; return objs.length == 0; } return false; } public static boolean notEmpty(Object obj) { return !isEmpty(obj); }
标签:static,return,Object,public,Java,isEmpty,obj,final,赋值 From: https://www.cnblogs.com/acm-bingzi/p/java_reflection_final.html