在这种情况下如何摆脱ifs?

时间:2018-04-22 10:12:45

标签: java oop design-patterns reflection

我有Criteria SQL请求的构建过程,但这种重复if()非常可怕。我想摆脱他们的。反思API可以帮助我,但我的斗争失败了。也许有些人帮我一个小例子。

@AllArgsConstructor
class PhoneSpecification implements Specification<Phone> {

    private final @NonNull PhoneFilter filter;

    @Override
    public Predicate toPredicate(Root<Phone> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        Predicate predicate = cb.conjunction();
        if (nonNull(filter.getId())) {
            predicate.getExpressions().add(cb.equal(root.get("id"), filter.getId()));
        }
        if (nonNull(filter.getNote())) {
            predicate.getExpressions().add(cb.like(root.get("note"), toLike(filter.getNote(), ANY)));
        }
        if (nonNull(filter.getNumber())) {
            predicate.getExpressions().add(cb.like(root.get("number"), toLike(filter.getNumber(), ANY)));
        }
        if (nonNull(filter.getStatus())) {
            predicate.getExpressions().add(cb.like(root.get("status"), toLike(filter.getStatus(), ANY)));
        }
        if (nonNull(filter.getOpName())) {
            predicate.getExpressions().add(cb.like(root.get("opName"), toLike(filter.getOpName(), ANY)));
        }
        if (nonNull(filter.getOpLogin())) {
            predicate.getExpressions().add(cb.like(root.get("opAccLogin"), toLike(filter.getOpLogin(), ANY)));
        }
        if (nonNull(filter.getOpPassword())) {
            predicate.getExpressions().add(cb.like(root.get("opPassword"), toLike(filter.getOpPassword(), ANY)));
        }
        if (nonNull(filter.getRegFrom()) && nonNull(filter.getRegTo())) {
            predicate.getExpressions().add(cb.between(root.get("regDate"), filter.getRegFrom(), filter.getRegTo()));
        }
        return predicate;
    }
}

我嘲笑这样的事情:

Lists.newArrayList(Phone.class.getDeclaredFields()).forEach(field -> {
    field.setAccessible(true);
    try {
        field.get(filter)
        //...
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
});

但我很困惑,我可以获得价值和类型,以及领域名称......

也许反思不是一个好方法,你知道的更好吗?设计模式还是其他什么?

此过滤器DTO:

@Data
class PhoneFilter {
    private Pageable pageable;
    private Integer id;
    private Timestamp regFrom;
    private Timestamp regTo;
    private String number;
    private String opLogin;
    private String opPassword;
    private String opName;
    private String status;
    private String note;
}

0 个答案:

没有答案