为来自不同包的对象创建一个通用转换器

我有5个Web服务,A,B,C,D和E.每个都有自动生成的对象具有完全相同的结构,但具有不同的名称和不同的包。

com.ws.a.carA contains parameters and com.ws.a.wheelA com.ws.b.carB contains parameters and com.ws.b.wheelB com.ws.c.carC contains parameters and com.ws.c.wheelC com.ws.d.carD contains parameters and com.ws.d.wheelD com.ws.e.carE contains parameters and com.ws.e.wheelE 

我想创建一个函数,可以将这些对象(和内轮)中的每一个转换为一个名为的对象

 com.model.car, 

但我不会有很多function,如:

 com.model.car convert(com.ws.a.objA obj) com.model.car convert(com.ws.b.objB obj) 

问题是,我无法为所有对象提供实现的通用接口,因为我不想手动更改自动生成的类(它们经常重新创建)。

我需要一种方法,可能是generics,来创建一个共同的function

 com.model.car convert(T obj) 

这将适用于所有类型的汽车,但我不知道如何实施它。

你可以使用reflection。 最简单,最干净的方法可能是使用Apache Common BeanUtils , PropertyUtils #copyProperties或BeanUtils #copyProperties 。

PropertyUtils #copyProperties将值从一个对象复制到另一个对象,其中字段名称相同。 因此,对于copyProperties(dest,orig),它会为两个对象中存在的所有字段调用dest.setFoo(orig.getFoo())。

BeanUtils #copyProperties也是这样做的,但是你可以注册转换器,以便在必要时将值从String转换为Int。 有许多标准转换器,但你可以注册自己的,在你的情况下com.ws.a.wheelA到com.model.wheel,或其他什么。

您还可以查看推土机

我认为你应该考虑使用reflection 。

使用commons beanutils库你可以做这个实用程序类:

 public class BeanUtilCopy { private static BeanUtilsBean beanUtilsBean; private static ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean(); static { convertUtilsBean.register(new Converter() { //2 public  T convert(Class type, Object value) { T dest = null; try { dest = type.newInstance(); BeanUtils.copyProperties(dest, value); } catch (Exception e) { e.printStackTrace(); } return dest; } }, Wheel.class); beanUtilsBean = new BeanUtilsBean(convertUtilsBean); } public static void copyBean(Object dest, Object orig) throws Exception { beanUtilsBean.copyProperties(dest, orig); //1 } 

当(1)beanUtilsBean使用转换器(2)将Wheel ** X **值传递给目标bean中的Wheel时。

使用样本:

  CarB carB = new CarB(); carB.setName("car B name"); carB.setWeight(115); WheelB wheelB = new WheelB(); wheelB.setName("wheel B name"); wheelB.setType(05); carB.setWheel(wheelB); Car car1 = new Car(); BeanUtilCopy.copyBean(car1, carB); System.out.println(car1.getName()); System.out.println(car1.getWeight()); System.out.println(car1.getWheel().getName()); System.out.println(car1.getWheel().getType()); 

输出:

车B名

115

轮B名