簡體   English   中英

為 Boolean 值調用 Java 構造函數中的方法

[英]Calling Methods in Java Constructor For Boolean Value

我目前正在對繼承的 Spring 啟動應用程序進行開發,其中一部分是發送 API POST 請求,其中包含 boolean 是否完成足球比賽( resulted )。 我注意到 class 的設計是這樣的:

//parent class
public class Fixture {

    private final FixtureType type;
    private final Team homeTeam;
    private final Team awayTeam;

    public Fixture(@JsonProperty("type") final FixtureType type,
                   @JsonProperty("homeTeam") final Team homeTeam,
                   @JsonProperty("awayTeam") final Team awayTeam

    ) {
        this.type = type;
        this.homeTeam = homeTeam;
        this.awayTeam = awayTeam;
    }

    public boolean isResulted() {
        return false;
    } 
    /* 
     other methods
    */
}  
//child class
public class Result extends Fixture {

    private final Outcome outcome;

    public Result(@JsonProperty("type") final FixtureType type,
                  @JsonProperty("homeTeam") final Team homeTeam,
                  @JsonProperty("awayTeam") final Team awayTeam,
                  @JsonProperty("outcome") final Outcome outcome) {

        super(type, homeTeam, awayTeam);
        this.outcome = outcome;
    }

    @Override
    public boolean isResulted() {
        return true;
    }
    /* 
     other methods
    */
}

在 Swagger 文檔中,請求指定"resulted": true需要是 JSON POST 請求中的字段。 現在我可以將該字段添加到構造函數中,但這意味着更改調用此構造函數的大量測試和代碼。 我的解決方案是在構造函數本身中調用isResulted()方法。 我以前從未這樣做過,但這有效。 從長遠來看,下面的這種設計是否會產生問題?

public class Result extends Fixture {

     private final boolean resulted;

     public Result (){
      super();
      resulted = isResulted();
     }

    @Override
    @JsonProperty("resulted")
    public boolean isResulted() {
        return true;
    }

}


我不明白擁有一個不在任何地方使用的私有字段的目的是什么。 我也不確定我是否理解您想要解決的問題。

有一種可能的方法既更靈活又與您以前的代碼兼容:

public class Result extends Fixture {

     private final boolean resulted;

     public Result (boolean resulted){
      super();
      this.resulted = resulted;
     }

     public Result (){
        this(true); // sets the default value
     }

    @Override
    @JsonProperty("resulted")
    public boolean isResulted() {
        return resulted;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM