欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java常用对象操作工具代码实例

时间:2021-03-25 09:17:15|栏目: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;
}

上一篇:详解java基于MyBatis使用示例

栏    目:JAVA代码

下一篇:spring Boot与Mybatis整合优化详解

本文标题:Java常用对象操作工具代码实例

本文地址:http://www.codeinn.net/misctech/87414.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有