簡體   English   中英

有沒有辦法檢查java中的類是否為空?

[英]Is there a way to check if a class is empty in java?

對不起,如果標題有點混亂,我真的不知道如何表達我想問的問題。

基本上,我正在對返回數據的數據庫進行 api 調用:

[{"profiles":{" testexample ":{"addresses":[{"city":" ","street1":" ","street2":"apt 320"}],"addressType":"HOME" ,"city":" ","dateOfBirth":" ","emailAddress1":" ","emailAddress2":" ","emailAddresses":[{"email":" ","preferred":1,"type ":"BUSINESS"},{"email":" ","preferred":0,"type":"PERSONAL"}],"firstName":" ","lastName":" ","phoneNumber":" ","phoneNumbers":[],"phoneType":"HOME","postalCode":" ","preferred":1,"street1":" ","street2":" "}]

當數據庫返回非空配置文件 {} 時,我下面的代碼可以正常工作。 我有以下 Java 類,如下所示:

public class Account {

    @JsonProperty("profiles")
    private Profiles profiles;

    @JsonProperty("profiles")
    public Profiles getProfiles() {
        return profiles;
    }

    @JsonProperty("testexample")
    public void setProfiles(Profiles profiles) {
        this.profiles = profiles;
    }

}
public class Profiles {

    @JsonProperty("testexample")
    private Profile testExample;

    @JsonProperty("testexample")
    public Profile getTestExample() {
        return testExample;
    }

    @JsonProperty("testexample")
    public void setTestExample(Profile testExample) {
        this.testExample = testExample;
    }

}
public class Profile {


    @JsonProperty("dateOfBirth")
    private String dateOfBirth;

    @JsonProperty("dateOfBirth")
    public String getDateOfBirth() {
        return dateOfBirth;
    }
    @JsonProperty("dateOfBirth")
    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

}

所以當我獲取數據時我想做的是檢查 getProfiles() 是否返回空,所以我不會調用該對象中的任何內容。

請注意,為了簡單起見,我省略了課程的其他部分,主要關注我想要的內容

這是我到目前為止所擁有的,當配置文件 {} 不為空時它可以工作

Account response = access.lookup(id, type); //This is to grab the response from the database, which is working.

response.getProfiles(); //This is the part that works when it has a profiles {} not empty, but fails on empty.

所以發生的是我沒有收到 response.getProfiles() 的錯誤,但是如果我嘗試執行 response.getProfiles().getDateOfBirth(),它不會工作,因為它會給出一個空指針異常,因為dateOfBirth 不存在。

如果 response.getProfiles() 為空,我想通過跳過它來避免調用任何內容。

您需要一些基本的空值檢查。 最基本的方法是分配一個新變量並檢查。

Profiles profiles = account.getProfiles();
if(profiles != null) {
   //dosomething with profiles.getDateOfBirth()
}

更“現代”的功能性 Java 方法是使用Optional類。

String dateOfBirth = Optional.ofNullable(account.getProfiles())
    .map(profile -> profile.getDateOfBirth)
    .orElse(null);

(關於你的例子的注釋:在 Account 類中,你有這個。

@JsonProperty("testexample")
public void setProfiles(Profiles profiles) {
    this.profiles = profiles;
}

這似乎是一個不正確的@JsonProperty注釋,可能會導致一些問題。 也就是說,沒有必要注釋 getter 和 setter。 該字段上的一個注釋就足夠了。)

暫無
暫無

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

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