属性初始化问题

假如有这样的一个类

public class Student {
    private int age;
public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

}

其构造方法并没有强制给age赋值,如果程序运行最终均没有为age赋值,那么age将保持其默认值0;因为基本类型并没有null这一说法。

乍一看这视乎很正常,但是这是一种隐患。因为age=0是我们系统所没有预料或者不允许的值。很可能写入到数据库中。

比如下面这个用Jersey构造的reset api。

    
@path("xxxx")
public Response modifyInfo( ....    @FormParam("useful_life") short useful_life,  @FormParam("security") short security,){
.....................
person.setUserLife(userful_life);
person.setSecurity(security); personService.modifyInfo(person, no); ....................

}

接受的参数useful_life,security 为基本类型,当用户提交的数据不包含其中时,默认为0,并不为null。

而modifyIfo方法为 person非null属性更新数据库信息。

因为useful_life,security赋予的默认值0,造成了数据库更新问题。更新了没有期望的值。

应该将接口中的userful_life ,security类型由short 修改为Short。