背景

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. 6. 合并排序数组 II

    6. Merge Two Sorted Arrays Description Merge two given sorted integer array A and B into a new sorte ...

  2. bootstrap datepicker显示日历

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

  3. C++程序设计方法3:移动构造函数

    移动拷贝构造函数 语法: ClassName(ClassName&&); 目的: 用来偷“临时变量”中的资源(比如内存) 临时变量被编译器设置为常量形式,使用拷贝构造函数无法将资源偷出 ...

  4. Flask 三方组件 Flask-Session

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

  5. Java 多线程 ReadWriteLock

    ReadWriteLock是JDK 1.5提供的读写分离锁,可以减少锁竞争.例如,线程A1.A2和A3进行写操作,线程B1.B2和B3进行读操作,如果使用重入锁或者内部锁,那么理论上所有读之间.读与写 ...

  6. UE4入门(三)

  7. input中autocomplete属性

    autocomplete="off":表示刷新页面时,input中的value值清空 <input type="text" id="q" ...

  8. 【暴力枚举&BFS】Flow Free @RMRC2017/upcexam5124

    时间限制: 1 Sec 内存限制: 128 MB 题目描述 Flow Free is a puzzle that is played on a 2D grid of cells, with some ...

  9. React进阶之高阶组件

    前言 本文代码浅显易懂,思想深入实用.此属于react进阶用法,如果你还不了解react,建议从文档开始看起. 我们都知道高阶函数是什么, 高阶组件其实是差不多的用法,只不过传入的参数变成了react ...

  10. jeffy-vim-v3.1.tar.gz

    下载链接: https://files.cnblogs.com/files/pengdonglin137/jeffy-vim-v3.1.tar.gz 1. 使用sublimemonokai配色 2. ...