Java常用对象操作工具代码实例
对象复制(反射法)
public static void copyProp(Object from, Object to, String... filterProp) { HashSet<String> filterSet = new HashSet<String>(Arrays.asList(filterProp)); Class<?> fromc = from.getClass(); Class<?> toc = to.getClass(); List<Field> to_fields = new ArrayList<Field>() ; while (toc != null) { to_fields.addAll(Arrays.asList(toc.getDeclaredFields())); toc = toc.getSuperclass(); } for (Field to_field : to_fields) { try{if (filterSet.contains(to_field.getName())||'serialVersionUID'.equals(to_field.getName())) { continue;}Field from_field = null;try{ from_field = fromc.getDeclaredField(to_field.getName());}catch (Exception e){ continue;}from_field.setAccessible(true);Object value = from_field.get(from);if(value==null){ continue;}to_field.setAccessible(true);to_field.set(to, value); }catch (Exception e){e.printStackTrace(); } } } 只copy有值对象 不需要copy的属性用filterProp 是能过反射属性注入方法实现,所有属性的名称类型必须一样
对象复制(fastJson转换)
单个
public static <T> T bean2OtherBean(Object bean, Class<T> tClass){return JSON.parseObject(JSON.toJSONString(bean),tClass);}
列表
public static <T> List<T> list2OtherList(List originList, Class<T> tClass){List<T> list = new ArrayList<>();if(!CollectionUtils.isEmpty(originList)){for (Object obj : originList) {T t = bean2OtherBean(obj,tClass);list.add(t);}}return list;}
fastjson实现,属性不一样必须用注解
对象转MAP
public static <K,V> Map<K,V> bean2map(Object obj) throws IllegalAccessException {Map<String, Object> map = new HashMap<>();Class<?> clazz = obj.getClass();for (Field field : clazz.getDeclaredFields()) {field.setAccessible(true);String fieldName = field.getName();Object value = field.get(obj);map.put(fieldName, value);}return (Map<K, V>) map;}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章:
1. IDEA的Mybatis Generator驼峰配置问题2. Python使用oslo.vmware管理ESXI虚拟机的示例参考3. IntelliJ IDEA设置条件断点的方法步骤4. IntelliJ Idea2017如何修改缓存文件的路径5. Intellij IDEA 旗舰版创建 Spring MVC 项目踩过的坑6. Java构建JDBC应用程序的实例操作7. Express 框架中使用 EJS 模板引擎并结合 silly-datetime 库进行日期格式化的实现方法8. 一篇文章带你了解JavaScript-对象9. javascript设计模式 ? 建造者模式原理与应用实例分析10. 浅谈SpringMVC jsp前台获取参数的方式 EL表达式
