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

后端 未结 8 489
天涯浪人
天涯浪人 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:39

    I tried this and it works without any issues to validate if the field is empty. I have answered your question partially as I haven't personally tried to add default values to attributes

    if(field.getText()!= null && !field.getText().isEmpty())
    

    Hope it helps

    0 讨论(0)
  • 2020-12-05 07:40

    Maybe check Hibernate Validator 4.0, the Reference Implementation of the JSR 303: Bean Validation.

    This is an example of an annotated class:

    public class Address {
    
        @NotNull 
        private String line1;
        private String line2;
        private String zip;
        private String state;
    
        @Length(max = 20)
        @NotNull
        private String country;
    
        @Range(min = -2, max = 50, message = "Floor out of range")
        public int floor;
    
            ...
    }
    

    For an introduction, see Getting started with JSR 303 (Bean Validation) – part 1 and part 2 or the "Getting started" section of the reference guide which is part of the Hibernate Validator distribution.

    0 讨论(0)
提交回复
热议问题