Re-using field from other object instance where the name of the fields match #890
Replies: 1 comment 3 replies
-
Hey @nandorholozsnyak! Unfortunately, nothing out of the box allows automatically copying fields from one class to another based on field name. This would normally require some sort of manual mapping, as in your example. Having said that, it's possible to do this using a little helper method. The idea is to find matching fields that exist in both classes, get the field value via reflection, and @Test
void example() {
final Address address = Instancio.create(Address.class);
final InstancioApi<OrderEntity> api = Instancio.of(OrderEntity.class);
copyFields(api, address);
final OrderEntity orderEntity = api.create();
assertThat(orderEntity.addressLine1()).isEqualTo(address.addressLine1());
// etc...
}
private static void copyFields(final InstancioApi<OrderEntity> api, final Address address) {
Stream.of(OrderEntity.class.getDeclaredFields()).forEach(orderField -> {
try {
Field addressField = Address.class.getDeclaredField(orderField.getName());
addressField.setAccessible(true);
api.set(field(OrderEntity.class, addressField.getName()), addressField.get(address));
} catch (NoSuchFieldException | IllegalAccessException e) {
// ignore
}
});
} It looks a bit hacky, but If the classes are large and involve many fields, it might be worth it. With a bit more work, it's also possible to make the There might be a better approach, but I can't think of one right now. I'll follow up if I come up with anything. |
Beta Was this translation helpful? Give feedback.
-
Hello there,
On Twitter a few days ago I asked a question, and I was routed to here, now I had the time to create an example for this question or use case. I went through the documentation and the different selectors, unfortunately I did not find anything related to this topic.
The use case is the following. I have two different types where one types lists a few attributes, but this type can not/is just no used in the other type as an embedded one, but its fields is replicated in the other type.
For example:
First type:
Second type:
If I create an instance of the Address type with Instancio just with a one liner, or with two lines in case of a shiny custom generator, can I somehow create the OrderEntity with Instancio as well where I do not have to use the
.set(field(
construction to set all fields to the Address attributes?Does Instancio support this use case, if yes how?
Thanks in advance.
Beta Was this translation helpful? Give feedback.
All reactions