欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于反射解决类复制的实现方法

程序员文章站 2023-12-16 10:50:28
假定一个类,类名是etybase,另一个类类名是etytwo,etytwo继承自etybase。现在要求etytwo的属性值从一个etybase中复制过来传统做法是复制代码...

假定一个类,类名是etybase,另一个类类名是etytwo,etytwo继承自etybase。现在要求etytwo的属性值从一个etybase中复制过来传统做法是

复制代码 代码如下:

view code

  public void copyety(etybase from, etybase to)
  {
to.accstatus = from.accstatus;
to.alarm = from.alarm;
to.alarmtype = from.alarmtype;
to.carnum = from.carnum;
to.devnum = from.devnum;
to.devicenum = from.devicenum;
to.direct = from.direct;
to.drivecode = from.drivecode;
to.gpsdata = from.gpsdata;
to.gpsenvent = from.gpsenvent;
to.gpsodo = from.gpsodo;
to.gpsspeed = from.gpsspeed;
to.gpsstatus = from.gpsstatus;
to.gpsrevtime = from.gpsrevtime;
to.gsmci = from.gsmci;
to.gsmci1 = from.gsmci1;
to.gsmloc = from.gsmloc;
to.gsmloc1 = from.gsmloc1;
to.iseffective = from.iseffective;
to.isjump = from.isjump;
to.isreply = from.isreply;
to.latitude = from.latitude;
to.launchstatus = from.launchstatus;
to.longitude = from.longitude;
to.msgcontent = from.msgcontent;
to.msgexid = from.msgexid;
to.msgid = from.msgid;
to.msglength = from.msglength;
to.msgtype = from.msgtype;
to.nowoverarea = from.nowoverarea;
to.nowstatus = from.nowstatus;
to.oil = from.oil;
to.pulsecount = from.pulsecount;
to.pulseodo = from.pulseodo;
to.pulsespeed = from.pulsespeed;
to.replycontent = from.replycontent;
to.revmsg = from.revmsg;
to.speed = from.speed;
to.status = from.status;
to.temperture = from.temperture;
to.username = from.username;
  }


这样子做有几点不好的地方

    etybase的属性改变时复制的属性也得改变,耦合较高;
    若etybase的属性比较多,那么这个复制方法将显得比较冗长,写的人手累。

 

如果用反射来做,我是这么做的

复制代码 代码如下:

view code

  public void copyety(etybase from, etybase to)
  {
//利用反射获得类成员
fieldinfo[] fieldfroms = from.gettype().getfields();
fieldinfo[] fieldtos = to.gettype().getfields();
int lento = fieldtos.length;

for (int i = 0, l = fieldfroms.length; i < l; i++)
{
    for (int j = 0; j < lento; j++)
    {
  if (fieldtos[j].name != fieldfroms[i].name) continue;
  fieldtos[j].setvalue(to, fieldfroms[i].getvalue(from));
  break;
    }
}
  }


反射可以解决上述的两个缺点,当类属性改变或增加时,此复制方法无需改变。当然这是要付出些许运行效率的。

上一篇:

下一篇: