There are frameworks that do a mapping between objects of different classes. Chech out the comments.
If you don't want to use a third-party library, you could write an over-simplified version of what those frameworks offer.
For instance, if the names of the fields are identical, and the difference is only in types, we could write a method(A a, B b, Rules r)
which would map a
to b
by the given rules1:
public static void copyFromAtoB(A a, B b, Map<String, Function<Object, Object>> rules) throws NoSuchFieldException, IllegalAccessException {
for (Field f : B.class.getDeclaredFields()) {
final String fName = f.getName();
final Object aValue = A.class.getDeclaredField(f.getName()).get(a);
f.set(b, rules.containsKey(fName) ? rules.get(fName).apply(aValue) : aValue);
}
}
The rules2 tell what function we should apply to a field in order to set the value correctly.
If there is no rule for a field, we assume the types are compatible.
final A a = new A(5, 6);
final B b = new B();
final Map<String, Function<Object, Object>> rules = new HashMap<>();
rules.put("b", i -> Double.valueOf((int)i)); // int -> Double
copyFromAtoB(a, b, rules);
1 Yes, that's a reflection approach - it might be costly and over-engineered, but it seems pretty flexible.
2 Rules are not well-defined because we take an Object
and return an Object
(Function<Object, Object>
).