我有很多像这样的servlet:
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;
// ...
}
}
我需要用数据填充Response对象,但它可以包含很多字段。 如何在不在每个servlet中编写许多response.fieldN = dataN
的情况下执行此操作?我不想为每个类编写构造函数,因为我仍然需要在构造函数中编写这样的赋值
也许有任何可以执行它的库,或者我可以使用的任何模式,或者为Response类生成构造函数的任何方式?
答案 0 :(得分:1)
也许Dozer bean mapper可以帮到你。一些例子:
Mapper mapper = new DozerBeanMapper();
DestinationObject destObject =
mapper.map(sourceObject, DestinationObject.class);
或
DestinationObject destObject = new DestinationObject();
mapper.map(sourceObject, destObject);
答案 1 :(得分:0)
我不知道任何能为你做这件事的图书馆。但是......你可以使用流利的构建器来简化Response
创建,并使它更容易......我认为更容易。
离。
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:我宁愿避免为Value Object / DTO类编写带有许多参数的构造函数,因为传递给构造函数的每个参数都应该被认为是必需的。
答案 2 :(得分:0)
如果所有Response
对象的字段数相同,则编写一个static function
并从不同的servlet调用它。 static function
将完成所有response.fieldN = dataN