欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-01-23 10:15:37|栏目:JAVA代码|点击:

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

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、测试结果如下:

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

总结

上一篇:使用Java制作一个简单的记事本

栏    目:JAVA代码

下一篇:Spring Boot利用Docker快速部署项目的完整步骤

本文标题:Java实现不同的类的属性之间相互赋值

本文地址:http://www.codeinn.net/misctech/49833.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有