背景

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. linux学习笔记 yum 在线管理软件包

    -y  如果yum在工作过程中需要使用者响应.这个参数可以直接回答yes #yum list 列出资源库中所有可安装或者可更新的rpm包 #yum perl 列出为perl的包 #yum perl* ...

  2. 大数据环境完全分布式搭建hbase-0.96.2-hadoop2

    1.上传hbase安装包 2.解压 3.配置hbase集群,要修改3个文件 (首先zookeeper集群已经安装好了 并且启动 hadoop启动) 注意:要把hadoop的hdfs-site.xml和 ...

  3. Django之模板1

    Django模板 一.变量(只需要记住两种特殊符号) {{ }} 和{% %} {{ }}表示变量,在模板渲染的时候替换成值,变量名由字母数字和下划线组成. {% %}表示逻辑相关的操作. 点(.)在 ...

  4. Idea创建一个Springboot单模块项目

    1.打开IDEA,创建新项目,选择Spring Initializr,选择SDK为你的java版本. 2.点击下一步,输入Artifact 3.点击下一步,选择web 4.finish 5.完成后id ...

  5. Kotlin基础(一)Kotlin快速入门

    Kotlin快速入门 一.函数 /* * 1.函数可以定义在文件最外层,不需要把它放在类中 * 2.可以省略结尾分号 * */ fun main(args: Array<String>) ...

  6. 关于 win10启动错误 Error:16

    那个软件报这个错误,就打开属性 -- 兼容性 -- 打勾以管理员身份运行

  7. mybatis查询到count(*)返回值

    resultType="int" <select id="num_List_" parameterType=" xxx" result ...

  8. phpExcel导入大数据量情况下内存溢出解决方案

    PHPExcel版本:1.7.6+ 在不进行特殊设置的情况下,phpExcel将读取的单元格信息保存在内存中,我们可以通过 PHPExcel_Settings::setCacheStorageMeth ...

  9. mysql:Cannot proceed because system tables used by Event Scheduler were found damaged at server start

    mysql 5.7.18 sqlyog访问数据库,查看表数据时,出现 Cannot proceed because system tables used by Event Scheduler were ...

  10. javascript对属性的操作

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...