背景

Bean的拷贝一直有一些类可以使用,比如Apache的org.apache.commons.beanutils.BeanUtils或者Spring的org.springframework.beans.BeanUtils

根据定义的白名单字段进行Bean的拷贝

我需要一个只拷贝我指定的字段的Bean拷贝,而Spring的org.springframework.beans.BeanUtils提供如下几个方法:



其中第2、3个是可以指定属性的,第2个指定可以通过Class指定,基本满足我的需求;第3个指定无须理会的字段。

我不想定义另外的类,或者另外的父类去指定部分属性,我想通过自己配置的白名单只拷贝白名单指定的属性:

package com.nicchagil.exercise.springbootexercise.util;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import org.springframework.beans.BeanUtils; public class BeanCopyUtils { /**
* 根据白名单字段拷贝Bean
*/
public static <T> T copyProperties(Object source, Class<T> clazz, String[] whiteProperties) {
List<String> ignorePropertiesList = BeanCopyUtils.getIgnoreProperties(clazz, whiteProperties); String[] ignoreProperties = new String[ignorePropertiesList.size()];
ignorePropertiesList.toArray(ignoreProperties); T target;
try {
target = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("通过Class实例化对象发生异常", e);
} BeanUtils.copyProperties(source, target, ignoreProperties);
return target;
} /**
* 根据白名单字段字段获取无须理会的字段
* @param clazz
* @param whiteProperties
* @return
*/
public static List<String> getIgnoreProperties(Class<?> clazz, String[] whiteProperties) {
List<String> allProperties = BeanCopyUtils.getAllProperties(clazz); if (allProperties == null || allProperties.size() == 0) {
return null;
} allProperties.removeAll(Arrays.asList(whiteProperties));
return allProperties;
} /**
* 获取全部属性名称
*/
public static List<String> getAllProperties(Class<?> clazz) {
PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz); if (propertyDescriptors == null || propertyDescriptors.length == 0) {
return null;
} List<String> properties = new ArrayList<String>();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
properties.add(propertyDescriptor.getName());
} return properties;
} }

单元测试:

package com.nicchagil.exercise.springbootexercise;

import org.junit.Test;

import com.nicchagil.exercise.springbootexercise.util.BeanCopyUtils;

public class BeanCopyUtilsTest {

	@Test
public void test() {
User user = new User();
user.setId(123);
user.setName("Nick Huang"); User userCopy = BeanCopyUtils.copyProperties(user, User.class, new String[] {"name"});
System.out.println("user : " + user);
System.out.println("userCopy : " + userCopy);
} public static class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
} }

【小工具】根据定义的白名单字段进行Bean的拷贝的更多相关文章

  1. 数据库表转换成javaBean对象小工具

    package test.utils; import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter; ...

  2. 2000条你应知的WPF小姿势 基础篇<45-50 Visual Tree&Logic Tree 附带两个小工具>

    在正文开始之前需要介绍一个人:Sean Sexton. 来自明尼苏达双城的软件工程师.最为出色的是他维护了两个博客:2,000Things You Should Know About C# 和 2,0 ...

  3. 开源小工具 酷狗、网易音乐缓存文件转mp3工具

    发布一个开源小工具,支持将酷狗和网易云音乐的缓存文件转码为MP3文件. 以前写过kgtemp文件转mp3工具,正好当前又有网易云音乐缓存文件需求,因此就在原来小工具的基础上做了一点修改,增加了对网易云 ...

  4. C#7.2——编写安全高效的C#代码 c# 中模拟一个模式匹配及匹配值抽取 走进 LINQ 的世界 移除Excel工作表密码保护小工具含C#源代码 腾讯QQ会员中心g_tk32算法【C#版】

    C#7.2——编写安全高效的C#代码 2018-11-07 18:59 by 沉睡的木木夕, 123 阅读, 0 评论, 收藏, 编辑 原文地址:https://docs.microsoft.com/ ...

  5. Windows虚拟地址转物理地址(原理+源码实现,附简单小工具)

                                                                                                        ...

  6. 这些小工具让你的Android 开发更高效

    在做Android 开发过程中,会遇到一些小的问题.尽管自己动手也能解决.可是有了一些小工具,解决这些问题就得心应手了,今天就为大家推荐一下Android 开发遇到的小工具,来让你的开发更高效. Vy ...

  7. Android 开发小工具之:Tools 属性 (转)

    Android 开发小工具之:Tools 属性 http://blog.chengyunfeng.com/?p=755#ixzz4apLZhfmi 今天来介绍一些 Android 开发过程中比较有用但 ...

  8. html小工具——文章注释编辑器

    在网上阅读文章时,读者时常会想针对某段文字写一些自己的感想,可惜大部分阅读网站并不提供这样的功能,读者往往只能将文本复制到本地或在线的编辑器中编辑注释,之后如果想在其他地方回顾这些注释也必须先本地安装 ...

  9. [apue] 一个查看当前终端标志位设置的小工具

    话不多说,先看运行效果: >./term input flag 0x00000500 BRKINT not in ICRNL IGNBRK not in IGNCR not in IGNPAR ...

随机推荐

  1. 无可奈何的开始了jquery的“奇淫技巧”

    转载请注明出处: https://home.cnblogs.com/u/zhiyong-ITNote/ 修改一个已有的项目,主要是前端方面,一般的项目后端都是处理好了的,不需要改也不能改,除非特殊需求 ...

  2. XamarinEssentials教程应用程序信息AppInfo

    XamarinEssentials教程应用程序信息AppInfo   很多应用程序都提供一个“关于”功能.该功能会向用户展示应用程序的基本信息,如版本号.应用程序名称等.这个功能可以通过Xamarin ...

  3. Pandas 学习记录(一)

    1.DataFrame 按照列和按照行进行索引数据 按照列索引 df[’column_name’] 按照行索引 df.loc[’row_key’] 或 df.iloc[index] 2.先行后列索引单 ...

  4. 4535 ACM 礼尚往来 数学排列组合

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=4535 题意:每个礼物都不相同的组合个数 数学规律: 将每个女友排序为1···n,对应的女友送男友的礼物排序 ...

  5. [SPOJ-CIRU]The area of the union of circles/[BZOJ2178]圆的面积并

    [SPOJ-CIRU]The area of the union of circles/[BZOJ2178]圆的面积并 题目大意: 求\(n(n\le1000)\)个圆的面积并. 思路: 对于一个\( ...

  6. [POJ3197]Stall Reservations (贪心)

    题意 (来自洛谷) 约翰的N(l<N< 50000)头奶牛实在是太难伺候了,她们甚至有自己独特的产奶时段.当 然对于某一头奶牛,她每天的产奶时段是固定的,为时间段A到B包括时间段A和时间段 ...

  7. Flask 三方组件 Flask-Session

    使用 from flask import session, Flask from flask_session import Session from redis import Redis app = ...

  8. 腾讯云CDN python SDK

    腾讯云CDN python SDK 博主在开发时偶尔要用到CDN,感觉适合学生党的应该是腾讯云的CDN了,还提供了每月10G的流量,博主平时学习使用已经足够了. 代码 #coding=utf-8 fr ...

  9. PAT基础6-5

    6-5 求自定类型元素的最大值 (10 分) 本题要求实现一个函数,求N个集合元素S[]中的最大值,其中集合元素的类型为自定义的ElementType. 函数接口定义: ElementType Max ...

  10. web.config中的ExtensionlessUrlHandler-Integrated-4.0

    对于像MVC这种比较特殊的URL,例如 www.store.com/books/GetById/2 因为没有文件后缀名,IIS通常会无法解析,返回403或者404错误.ASP.NET v4.0增加了新 ...