栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

对象复制(反射法)

public static void copyProp(Object from, Object to, String... filterProp) {
    HashSet filterSet = new HashSet(Arrays.asList(filterProp));
    Class fromc = from.getClass();
    Class toc = to.getClass();
    List to_fields = new ArrayList() ;
    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 bean2OtherBean(Object bean, Class tClass){
	return JSON.parseObject(JSON.toJSonString(bean),tClass);
}

列表

public static  List list2OtherList(List originList, Class tClass){
	List 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  Map bean2map(Object obj) throws IllegalAccessException {
	Map 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) map;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/129899.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号