简体   繁体   English

Java 中基于条件的生成器

[英]Condition based builder in Java

I have a field that needs to be checked.我有一个字段需要检查。 If the field matches put it to builder if not, don't put it to builder.如果该字段匹配,则将其提交给构建器,如果不匹配,则不要将其提交给构建器。

@Data
@Builder
public class UserSchool {
    private final Long UserId;
    private final String school;
    private final Optional<String> lunch;

}

I need to check if user belongs to "high school", then add parameter lunch to builder.我需要检查用户是否属于“高中”,然后将参数 lunch 添加到构建器。 If user doesn't belong to "high school" don't add parameter to builder.如果用户不属于“高中”,请不要向构建器添加参数。

if(user.school.name().equals(School.high_school.name())){
            Deposit.builder()
                    .lunch(request.getLounchName());
        }

UserSchool userSchool = UserSchool.builder()
                .UserId(Long.valueOf(user.UserId.id))
                .school(request.getUserSchool())
                .build();

I have come up with this code above and lunch parameter is null although it should be there.我在上面提出了这段代码,午餐参数是null ,尽管它应该在那里。

When I add it to builder without if statement like this:当我在没有 if 语句的情况下将它添加到构建器时:

UserSchool userSchool = UserSchool.builder()
                .UserId(Long.valueOf(user.UserId.id))
                .school(request.getUserSchool())
                .lunch(request.getLounchName())
                .build();

It works but I need to be able to check condition.它有效,但我需要能够检查条件。 What am I missing?我错过了什么?

You shouldn't use an Optional type as a class field, generally only return types or wrappers to nullable return types.您不应该使用 Optional 类型作为 class 字段,通常只返回类型或包装器到可为 null 的返回类型。

If I understand the question, though, you're looking for this不过,如果我理解这个问题,你正在寻找这个

UserSchool.Builder builder = UserSchool.builder()
                .UserId(Long.valueOf(user.UserId.id))
                .school(request.getUserSchool());
if (condition) {
   builder.lunch(..);
}
UserSchool userSchool = builder.build();

Or或者

String lunch = condition ? "some value" : null;
UserSchool.Builder builder = UserSchool.builder()
                .UserId(Long.valueOf(user.UserId.id))
                .lunch(lunch)
                .school(request.getUserSchool())
               .build();

Or simply add a method to the class, not use a nullable field或者干脆给 class 添加一个方法,不要使用可为空的字段

public Optional<String> getLunch() {
    return condition ? Optional.of("some value") : Optional.empty();
} 

The problem with the if statement before the builder is that you've used some other builder, but never captured its return value to use later on构建器之前的 if 语句的问题是您使用了其他构建器,但从未捕获其返回值以供以后使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM