0

我得到这个语句的空指针异常。

accountList.getTrxnList().getTrxns().size() > 0

accountList 是我从外部 API 调用中获得的帐户列表。而且我确信返回了一个非空的 accountList 值。但我不相信 getTrxns() 有任何值。所以在处理之前我检查是否有任何 Trxns 但这也会导致空指针异常。

这是我的模型课

public class AccountList{

    private TrxnList trxnList;

    public static class TrxnList {

        private List<Trxn> trxns;

        public List<Trxn> getTrxns() {
            return trxns;
        }
    }
}

有人可以指出为什么这会引发空指针异常吗?我对此进行了一些研究,因此即使 trxns 列表中没有项目,我也无法理解此引发的空指针异常。

谢谢你。

4

3 回答 3

4

您的 List 未实例化,仅声明。你需要把:

private List<Trxn> trxns = new ArrayList<>(); 
于 2019-11-05T08:45:58.920 回答
2

您也可以捕获NullPointerException,但我同意其他评论者的观点,即通过实例化列表来解决异常。

public class AccountList{

    private TrxnList trxnList;

    public static class TrxnList {

        private List<Trxn> trxns;

        public List<Trxn> getTrxns() {
            try
            {
                return trxns;
            }
            catch(NullPointerException e)
            {
                // handle the list==null case here
                // maybe instantiate it here if it's not:
                trxns = new ArrayList<>();
            }
        }
    }
}
于 2019-11-05T09:54:44.770 回答
1
public class AccountList{

    private TrxnList trxnList;

    public static class TrxnList {

        private List<Trxn> trxns;

        public List<Trxn> getTrxns() {
            return Optional.ofNullable(trxns).orElse(new ArrayList())
        }
    }
}
于 2019-11-05T09:18:33.713 回答