zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    使用 ReplicationHandler 设置一个中继器(Repeater)
    SpringSource通过Spring for Android 1.0将Spring Framework引入到Android上
    Lotus Quickr 8.5.1 for Domino 中目录服务的配置详解
    Pdf文件编辑攻略
    Android 4.1最终版SDK和ADT Plugin全线发布
    JXL copySheet 的一个BUG
    Spring Mobile 1.0发布
    jQuery 1.8、1.9与2.0特性概览,2.0将移除对IE6/7/8的支持
    Regsvr32命令修复IE 重装IE
    系统性分析性能问题与调优方法
  • 原文地址:https://www.cnblogs.com/pigmen/p/14088623.html
Copyright © 2011-2022 走看看