温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

利用Java怎么对对象进行操作

发布时间:2020-12-10 14:16:08 来源:亿速云 阅读:138 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关利用Java怎么对对象进行操作,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

对象复制(反射法)

public static void copyProp(Object from, Object to, String... filterProp) {
    HashSet<String> filterSet = new HashSet<String>(Arrays.asList(filterProp));
    Class<&#63;> fromc = from.getClass();
    Class<&#63;> 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<&#63;> 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怎么对对象进行操作就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI