您的位置:首页 > 编程语言 > Java开发

Java:通过反射复制父类字段到子类。

2016-09-07 13:57 405 查看
有些时候需要建立子类继承于父类,尤其是java里面很多类是用mybatis generator生成的。通过父类构造子类,好像很麻烦,要逐个字段进行赋值(反正我没有找到其他好办法)。

想到用反射复制的方式来实现。通过研究,做到了。主要是用了fastjson里面的东西。估计已经有其他类库实现了这个功能,可惜我不知道,只能自己搞。

  

@Test
public void Test() throws InvocationTargetException, IllegalAccessException {

BaseClass baseClass = new BaseClass();
SubClass subClass=new SubClass();

baseClass.setB(true);
baseClass.setI(1010);
baseClass.setIs(false);
baseClass.setWhatname("fgq");

Integer i=0;
List<Integer> ii=new ArrayList<Integer>();
ii.add(1);
ii.add(10);
ii.add(100);
ii.add(1000);
ii.add(10000);

StopWatch stopWatch=new StopWatch();

stopWatch.reset();;
stopWatch.start();
Copyer.Copy(baseClass, subClass);
stopWatch.stop();
System.out.println("cache the reflection:"+String.valueOf(stopWatch.getTime()));

for (int j = 0; j < ii.size(); j++) {
i=0;
stopWatch.reset();;
stopWatch.start();
while ( i<ii.get(j)) {

Copyer.Copy(baseClass, subClass);
subClass.setBirthday(new Date());
i+=1;
}
stopWatch.stop();
System.out.println(String.format("%s  %s",ii.get(j),String.valueOf(stopWatch.getTime())));
}

System.out.println(JSON.toJSONString(subClass,SerializerFeature.PrettyFormat,SerializerFeature.UseISO8601DateFormat));

}


View Code

性能结果为:

cache the reflection:120
1 1
10 7
100 53
1000 139
10000 634

感觉还行。呵呵
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: