1.
BeanUtils.copyProperties(source,target);
demo:
Log log = new Log();
log.setName("姓名");
log.setColumn("name");
BeanUtilsDemoLog beanUtilsDemoLog = new BeanUtilsDemoLog();
BeanUtils.copyProperties(log,beanUtilsDemoLog);
System.out.println(beanUtilsDemoLog);
上面两个类内部属性名一样:
可以看到数据拷贝过来了
2.
自定义工具类
@SneakyThrows
public void customBeanUtilsCopyProperties(Object source , Object target ) {
if (null == source || null == target) {
Objects.requireNonNull(source,"参数错误");
}
Class<?> sourceClazz = source.getClass();
Class<?> targetClazz = target.getClass();
//source 所有读的方法
Method[] sourcePublicReadMethods = getPublicReadOrWriteMethods(sourceClazz,true);
// target 所有写的方法
Method[] targetPublicReadMethods = getPublicReadOrWriteMethods(targetClazz,false);
// 读到非 null 的就写入
for (Method sourceMethod : sourcePublicReadMethods) {
// invoke (Object ,args)
if (null != sourceMethod) {
Object sourceValue = sourceMethod.invoke(source, null);
if (null != sourceValue) {
// 找到目标的对应方法写入
String methodName = sourceMethod.getName();
// 过滤掉 toString 方法
if (methodName.startsWith("toString")) {
continue;
}
// 将get 换成set
String setMethodName = methodName.replace("get", "set");
for (Method writeMethod : targetPublicReadMethods) {
if (null != writeMethod && writeMethod.getName().equals(setMethodName)) {
// 写入
writeMethod.invoke(target,sourceValue);
}
}
}
}
}
}
/**
* @Description: 获取 Public 读,写的方法(get ,set方法)
*
* - getMethods(): 获得类的public类型的方法
* - getMethod(String name, Class[] params): 获得类的特定方法,name参数指定方法的名字,params参数指定方法的参数类型
*- getDeclaredMethods(): 获取类中所有的方法(public、protected、default、private)
* - getDeclaredMethod(String name, Class[] params): 获得类的特定方法,name参数指定方法的名字,params参数指定方法的参数
*/
private static Method[] getPublicReadOrWriteMethods(Class<?> clz,boolean isGet) {
if (!ReflectUtil.isPackageAccessible(clz)) {
return new Method[0];
}
Method[] result = clz.getMethods();
for (int i = 0; i < result.length; i++) {
Method method = result[i];
// 方法不在此类
if (!method.getDeclaringClass().equals(clz)) {
result[i] = null;
}
else {
try {
// 修饰符是否是 public的 method
method = MethodFinder.findAccessibleMethod(method);
String methodName = method.getName();
// get 方法
if (isGet) {
result[i] = methodName.startsWith("get")
? method
: null;
// set 方法
}else{
result[i] = methodName.startsWith("set")
? method
: null;
}
}
catch (NoSuchMethodException exception) {
}
}
}
return result;
}
测试代码:
Log log = new Log();
log.setName("姓名");
log.setColumn("name");
BeanUtilsDemoLog beanUtilsDemoLog = new BeanUtilsDemoLog();
customBeanUtilsCopyProperties(log ,beanUtilsDemoLog);
System.out.println(beanUtilsDemoLog);