Reputation: 768
I have many servlets like this:
public class DoSmthServlet extends AbstractDTOServlet<DoSmthServlet.Params> {
@Override
public Response service(Params params) throws Exception {
// Some logic...
Response response = new Response();
response.field1 = data1;
response.field2 = data2;
// ...
return response;
}
public static class Params implements DomainDTO {
public long arg1;
public boolean arg2;
// ...
}
public static class Response implements DomainDTO {
public String field1;
public long field2;
// ...
}
}
I need to fill Response object with data, but it can contain really many fields. How to do it without writing many response.fieldN = dataN
in each servlet? I don't want to write constructors for each class because I'll still have to write such assignments in constructors.
Maybe there is any library that can do it, or any pattern that I can use, or any way to generate constructors for Response classes?
Upvotes: 1
Views: 1295
Reputation: 148
If number of fields are same for all the Response
object then write one static function
and call it from different servlets. static function
will do all response.fieldN = dataN
Upvotes: 0
Reputation: 3176
I don't know any library that can do it for you. But... you can use fluent builder which will simplify Response
creation and make it a little bit... easier I think.
ex.
public class ResponseBuilder {
private Response response = new Response();
public ResponseBuilder withField1(String field1) {
response.field1 = field1;
return this;
}
public ResponseBuilder withField2(String field2) {
response.field2 = field2;
return this;
}
public Response build() {
return response;
}
}
// usage
Response response = Response.builder.withField1("a").withField2("b").build();
BTW: I would rather avoid writing constructor with many arguments for a Value Object/DTO class, because every argument passed to constructor should be considered as required.
Upvotes: 0
Reputation: 414
Maybe Dozer bean mapper can help you. Some example:
Mapper mapper = new DozerBeanMapper();
DestinationObject destObject =
mapper.map(sourceObject, DestinationObject.class);
or
DestinationObject destObject = new DestinationObject();
mapper.map(sourceObject, destObject);
Upvotes: 1