Java - 当不存在 属性 时,代码总是会抛出空指针异常?

Java - code will always throw a Null Pointer Exception when no Property is present?

我继承了以下 java 代码,它从 properties file 获取 property 的值:

    String personName = this.properties.getFilePropertty("person.name");
    if (personName != null) {
       // do something else
    } else {
        // do something
    }

上述流程中的预期行为是 personName 将从属性文件中检索,或者如果不存在则作为 null 返回,并进行相应处理。

然而,当 属性 不存在时,getFileProperty() 方法中会抛出异常(如下所示)。

如何解决此问题以实现预期的行为?

getFileProperty():

            public String getFileProperty(String name) throws SystemPropertiesException {
            
            return Optional.ofNullable( this.properties.getProperty(name, null) )
            .orElseThrow(()->new PropertiesException("Can not get property!"));
            
             }

注意 - 上面代码中调用的 getProperty() 方法是 java utils getProperty 方法。

你可以使用 try catch

try{
    String personName = this.properties.getFilePropertty("person.name");
    //if it's not null there will be no exception so you can directly use the personName 
    
}catch(SystemPropertiesException ex){
    //else there is an exception to handle here 
}

您应该将代码包装在 try catch 块中。

try {
    String personName = this.properties.getFileProperty("person.name");
    // do something else
} catch (PropertiesException exception) {
    // do something
}

编辑:或者为 .getFileProperty()

提供默认值
String personName = this.properties.getFilePropertty("person.name", "NO_VALUE_FOUND");
if (!personName.equals("NO_VALUE_FOUND")) {
    // do something else
} else {
    // do something
}