I have 5 webservices, A, B, C, D, and E. Each has autogenerated objects of the exact same structure, but with different names and in different packages.
com.
I think you should consider using reflection.
Using commons beanutils library you may do this utility class:
public class BeanUtilCopy {
private static BeanUtilsBean beanUtilsBean;
private static ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
static {
convertUtilsBean.register(new Converter() { //2
public <T> T convert(Class<T> 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
}
When (1) beanUtilsBean use the converter (2) to pass the Wheel**X** values to the Wheel in destination bean.
Use sample:
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());
The output:
car B name
115
wheel B name
5
You can use reflection for this. The easiest and cleanest way would probably be to use Apache Common BeanUtils, either PropertyUtils#copyProperties or BeanUtils#copyProperties.
PropertyUtils#copyProperties copies the values from one object to another, where the field names are the same. So with copyProperties(dest, orig), it calls dest.setFoo(orig.getFoo()) for all fields which exist in both objects.
BeanUtils#copyProperties does the same, but you can register converters so that the values get converted from String to Int, if necessary. There are a number of standard converters, but you can register your own, in your case com.ws.a.wheelA to com.model.wheel, or whatever.
You can also check out Dozer