反射小工具

一、类的复制

  copyProperties(Object sourceObject,Object targetObject);

  ps:时间不够了,这个很糙,很多情况都还没有考虑。下次有时间了再好好写一个

  

public void copyProperties(Object sourceObject,Object targetObject){
  /*
  * 首先获取到传递过来的两个类的Class对象
  */
  Class sourceClass = sourceObject.getClass();
  Class targetClass = targetObject.getClass();

  /*
  * 获取到对象中的所有属性
  * getFields()获得某个类的所有的公共(public)的字段,包括父类。
  *  
  * getDeclaredFields()获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段
  *
  * 在类中设置属性的时候一般都是设置为private,所以这里使用getDeclaredFields()方法
  */
  Field[] sourceFields = sourceClass.getDeclaredFields(); //注意,这个地方需要引入反射的包
  Field[] targetFields = targetClass.getDeclaredFields();

  /*
  * 获取到类中的所有属性时,就有两种处理方法
  * 一、嵌套循环
  * 二、单个循环
  */
  boolean flag = true;
  if(flag) {
  //嵌套循环
  if(sourceFields != null && sourceFields.length >0){
    if(targetFields != null && targetFields.length > 0) {
      //如果类中有属性,那么嵌套循环
      for(Field sourceField : sourceFields) {
        for(Field targetField : targetFields) {
          //获取到初始类的属性名称
          String sourceFieldName = sourceField.getName();
          Class sourceFieldType = sourceField.getType();
          //获取到目标类的属性名称
          String targetFieldName = targetField.getName();
          Class targetFieldType = targetField.getType();
          //判断类名是否一样
          if(sourceFieldName.equals(targetFieldName) && sourceFieldType.equals(targetFieldType)) {
            //如果一样,那么就执行复制

            /**
            * 在复制这个地方,还有一个问题
            * 如果说目标的对象该属性有值,那么要不要重新赋值
            * 这个地方加一个判断即可
            */
            String getMethodName = "get" + sourceFieldName.substring(0) + sourceFieldName.substring(1); //substring包左不包右
            String setMethodName = "set" + sourceFieldName.substring(0) + sourceFieldName.substring(1); //substring包左不包右


            try {
              //通过方法名称获取到类中的方法
              Method getMethod = sourceClass.getMethod(getMethodName);
              /*
              * 获取到方法之后,直接执行
              * method.invoke(Object,args);
              * Object : 需要执行这个方法的对象
              * args : 参数
              */
              Object getMethodValue = getMethod.invoke(sourceObject);

              Method setMethod = targetClass.getMethod(setMethodName, targetFieldType);
              setMethod.invoke(targetObject, getMethodValue);
            } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              } //因为是getXxx()所以不需要
      }else {

  

      }
}
}
}else {
//如果该类中没有属性,那么这个方法就没有意义,直接返回
return;
}
}else {
//如果该类中没有属性,那么这个方法就没有意义,直接返回
return;
}
}else {
//单个循环
}
}

原文地址:https://www.cnblogs.com/Chang1ng/p/7383505.html