为什么我的字符串不接受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
您需要添加空校验为mapper
以及chave
。
if (mapper!= null && chave != null && !"".equals(chave) {
// do something
}
mapper.getChave(chave.trim())
^ ^ possible places for NPE.
Mapper为null,idk为什么。是一个Spring存储库和我的代码:'@Autowired Mapper映射器;' –
你实例化你的类PlanilhaReader的对象吗?即在代码中的任何位置执行'新的PlanilhaReader()'? –
我正在运行没有Spring注释的jUnit单元测试。谢谢。 –
你需要检查chave
是否为空前修剪,或做其他事情(我假设mapper
预先初始化和不空,但你应该检查)
eg
if (chave != null && !"".equals(chave.trim()) {
// now do something
}
您可能会发现使用类似Apache Commons StringUtils.isNotBlank(String)
的东西更容易(更直观)。有关文档,请参阅here。
linha.keySet()
中有一个空字符串参考。
最有可能的chave
或mapper
值是零,你是呼吁他们trim()
和.getChave()
分别导致空指针
'chave'的值不为空或不为空,我有一个nullPointerException –
@DanielaMarquesdeMorais,那么你可以参考我的答案。 –
@DanielaMarquesdeMorais然后检查'mapper'的值。尝试'mapper'的打印值 – silentprogrammer
跟踪代码更改为空字符串 “”:你可以改变 “” 到任何你喜欢的
String novaChave = mapper.getChave((chave == null ? "" : chave).trim());
NULL是什么 - 映射器或蔡夫? – DaveH
'mapper'初始化了吗? “chave”的价值是什么? – Stefan
确保在你调用它的方法之前,String对象不是null。代码中的行号是什么? –