为什么我的字符串不接受空值?



我需要字符串接收空值,如果在mapper.getChave中找不到它,则返回什么。我做什么?如果我只得到nullPointerException

for(String chave : linha.keySet()) {
                //Processa chave
                String novaChave = mapper.getChave(chave.trim());
                if (!(novaChave == null || novaChave.isEmpty())) {
                    //Processa valor
                    String novoValor = linha.getString(chave);
                    temp.append(novaChave, novoValor);
                }
                else {
                    extras.append(chave, linha.getString(chave));
                }
            }

日志

java.lang.NullPointerException
    at oknok.validacao.readers.PlanilhaReader.processaAtributosPlanilha(PlanilhaReader.java:237)

237路是

String novaChave = mapper.getChave(chave.trim());

**更新:第一次循环运行时,我有一个空指针,chave包含一个值

System.out.println(chave.isEmpty() + "t" + chave + "t" + chave.trim());

输出

false   Veículo Veículo
您需要

mapperchave添加空检查。

if (mapper!= null && chave != null && !"".equals(chave) {
    // do something
}

mapper.getChave(chave.trim())
       ^              ^   possible places for NPE.

最有可能的是 chavemapper 的值为 null,并且您分别对它们调用 trim().getChave() 导致空指针

您需要

在修剪它或执行其他任何操作之前检查chave是否为 null(我假设mapper是预先初始化的而不是 null,但您也应该检查一下)

例如

if (chave != null && !"".equals(chave.trim()) {
   // now do something
}

您可能会发现使用类似Apache Commons StringUtils.isNotBlank(String)之类的东西更容易(更直观)。有关文档,请参阅此处。

linha.keySet() 中有一个空字符串引用。

遵循代码将空字符串更改为":您可以将"更改为您喜欢的任何内容

String novaChave = mapper.getChave((chave == null ? "" : chave).trim());

最新更新