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

问题描述:

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

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包含a值

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

输出

false Veículo Veículo 
+0

NULL是什么 - 映射器或蔡夫? – DaveH

+0

'mapper'初始化了吗? “chave”的价值是什么? – Stefan

+0

确保在你调用它的方法之前,String对象不是null。代码中的行号是什么? –

您需要添加空校验为mapper以及chave

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

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

Mapper为null,idk为什么。是一个Spring存储库和我的代码:'@Autowired Mapper映射器;' –

+0

你实例化你的类PlanilhaReader的对象吗?即在代码中的任何位置执行'新的PlanilhaReader()'? –

+1

我正在运行没有Spring注释的jUnit单元测试。谢谢。 –

你需要检查chave是否为空修剪,或做其他事情(我假设mapper预先初始化和空,但你应该检查)

eg

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

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

linha.keySet()中有一个空字符串参考。

最有可能的chavemapper值是零,你是呼吁他们trim().getChave()分别导致空指针

+0

'chave'的值不为空或不为空,我有一个nullPointerException –

+0

@DanielaMarquesdeMorais,那么你可以参考我的答案。 –

+1

@DanielaMarquesdeMorais然后检查'mapper'的值。尝试'mapper'的打印值 – silentprogrammer

跟踪代码更改为空字符串 “”:你可以改变 “” 到任何你喜欢的

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