温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java实现不同的类的属性之间相互赋值

发布时间:2020-09-09 18:31:47 来源:脚本之家 阅读:158 作者:徐刘根 栏目:编程语言

在开发的时候可能会出现将一个类的属性值,复制给另外一个类的属性值,这在读写数据库的时候,可能会经常的遇到 ,特别是对于一个有继承关系的类的时候,我们需要重写很多多余的代码,下面有一种简单的方法实现该功能

1、首先有两个类,两个类之间有相同的属性名和类型,也有不同的属性名很类型:

public class ClassTestCopy2 {
  private int id;
  private String name;
  private String password;
  private String sex;
  private String age;
  //get和set方法
}
public class ClassTestCopy1 {
  private int id;
  private String name;
  private String password;
  //get和set方法
}

2、下边的就是实现该功能的方法体:

public static void Copy(Object source, Object dest) throws Exception {
    // 获取属性
    BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);
    PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
    BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), java.lang.Object.class);
    PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();
    try {
      for (int i = 0; i < sourceProperty.length; i++) {
        for (int j = 0; j < destProperty.length; j++) {
          if (sourceProperty[i].getName().equals(destProperty[j].getName())) {
            // 调用source的getter方法和dest的setter方法
            destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
            break;
          }
        }
      }
    } catch (Exception e) {
      throw new Exception("属性复制失败:" + e.getMessage());
    }
  }

3、下边进行测试:

public static void main(String[] args) {
    ClassTestCopy1 c1 = new ClassTestCopy1(1205030213, "name:xuliugen","password:123456");
    ClassTestCopy2 c2 = new ClassTestCopy2();
    try {
      CopyBeanParamsTest.Copy(c1, c2);
      System.out.println("-------------c1----------------");
      System.out.println(c2.getId());
      System.out.println(c2.getName());
      System.out.println(c2.getPassword());
      System.out.println(c2.getSex());
      System.out.println(c2.getAge());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

4、测试结果如下:

Java实现不同的类的属性之间相互赋值

可知具有相同属性名和类型的属性被赋值,剩下的没有被匹配到的结果则为NUll;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对亿速云的支持。如果你想了解更多相关内容请查看下面相关链接

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI