Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

后端 未结 8 520
天涯浪人
天涯浪人 2020-12-05 06:57

I need to make sure that no object attribute is null and add default value in case if it is null. Is there any easy way to do this, or do I have to do it manually by checkin

8条回答
  •  星月不相逢
    2020-12-05 07:22

    You need to manually filter input to constructors and setters. Well... you could use reflection but I wouldn't advise it. Part of the job of constructors and setters is to validate input. That can include things like:

    public void setPrice(double price) {
      if (price < 0.0d) {
        throw new IllegalArgumentException("price cannot be negative " + price);
      }
      this.price = price;
    }
    

    and

    public void setName(String name) {
      if (name == null) {
        throw new NullPointerException("name cannot be null");
      }
      this.name = name;
    }
    

    You could use wrapper functions for the actual check and throwing the exception.

提交回复
热议问题