ITPub博客

首页 > IT职业 > IT职场 > Java对象拷贝

Java对象拷贝

IT职场 作者:rorog 时间:2021-09-09 09:55:00 0 删除 编辑

public static void copy(Object src , Object tar){
try {
Class> srcClazz = src.getClass();
Class> tarClazz = tar.getClass();
Field[] srcClazzDeclaredFields = srcClazz.getDeclaredFields();
for(Field srcField : srcClazzDeclaredFields){
String srcFieldNameBefore = srcField.getName();
String srcFieldNameFirstUp = srcFieldNameBefore.substring(0,1).toUpperCase()

  • srcFieldNameBefore.substring(1,srcFieldNameBefore.length());
    Method srcMethod = null;
    Method tarMethod = null;
    String getMethodName = "get" + srcFieldNameFirstUp;
    String setMethodName = "set" + srcFieldNameFirstUp;
    Class reType = null;
    try {
    srcMethod = srcClazz.getDeclaredMethod(getMethodName);
    }catch (Exception e){}
    if(srcMethod != null){
    try {
    reType = srcMethod.getReturnType();
    tarMethod = tarClazz.getDeclaredMethod(setMethodName , reType);
    }catch (Exception e){}
    if(tarMethod != null){
    Object obj = srcMethod.invoke(src);
    tarMethod.invoke(tar,obj);
    }
    }
    }
    }catch (Exception e){
    e.printStackTrace();
    }
    }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2976/viewspace-2814356/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-09-12

  • 博文量
    90
  • 访问量
    578