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

I need to make sure that no object attribute is null and add defautl value in case if it is null. Is there any easy way to do this, or do I have to do it manually by cheking every attrute by its getter and setters?

-------------Problems Reply------------

You can use reflection to iterate over the object's field, and set them. You'd obviously need some sort of mapping between types or even field names and required default values but this can be done quite easily in a loop. For example:

for (Field f : obj.getClass().getFields()) {
if (f.get(obj) == null) {
f.set(obj, getDefaultValueForType(f.getType()));

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;


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

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

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 {

private String line1;
private String line2;
private String zip;
private String state;

@Length(max = 20)
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.

You can create a function that returns a boolean value and checks every attribute. You can call that function to do the job for you.

Alternatively, you can initialize the object with default values. That way there is no need for you to do any checking.

I don't have enough context to give you a correct answer, but I'll suggest you to make you code immutable as much as possible. Use public final fields. No more getters or setters : every field has to be defined by the constructor. Your code is shorter, more readable and prevents you from writing code with side effects.

It doesn't prevent you from passing null arguments to your constructor though... You can still check every argument as suggested by @cletus, but I'll suggest you to throw IllegalArgumentException instead of NullPointerException that doesn't give no new hint about what you've done.

Anyway, that's what I do as much as I can and it improved my code (readability, stability) to a great extend. Everyone in my team does so and we are very happy with that. We learned that when we try to write some erlang code where everything is immutable.

Hope this helps.

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

Category:java Views:3 Time:2010-01-27
Tags: java null

Related post

  • Checking if a field allows null values in Django 2012-03-22

    I'm writing generic functions (using hasattr, setattr, getattr ...), in order to manage and update field values for a given field field_name of a certain model? Is there a way to check if the field my_model.field_name allows null values? ------------

  • Java method to assign object field values with Reflection 2011-09-22

    I was wondering whether it would be possible to have something like the following in Java: public class MyClass { private String name; private Integer age; private Date dateOfBirth; // constructors, getters, setters public void setField(String aField

  • How to check if object is undefined/null 2012-04-20

    This question has come up a lot but I can't make it work. I have 5 divs, I want to hide the div before the last one who was used. So If the user clicks somewhere in div 1, and then clicks somewhere in div 2, div 1 fades out (all of this after an Ajax

  • When/how often to check whether object is null 2009-11-02

    I was writing some code and while unit testing I got a Null Pointer Exception...Now I'm wondering how often should we be checking that object is not null before doing get operations on it? For example, code was: HashMap paramMap = new HashMap(); getS

  • how to check a string is not null 2011-03-31

    if(string.equals("")) { } how to check the string is not null if(!string.equals("")) { } ??? --------------Solutions------------- Checking for null is done via if (string != null) If you want to check if its null or empty - you'd need if (string != n

  • GAE/JDO: How to check whether a field in a detached object was loaded 2010-03-21

    My DAO detaches and then caches certain objects, and it may retrieve them with different fetch groups. Depending on which fetch group was used to retrieve the object, certain fields of that object may be available, or not. I would like to be able to

  • Looking for Java spell checker library 2009-02-18

    I am looking for an open source Java spell checking library which has dictionaries for at least the following languages: French, German, Spanish, and Czech. Any suggestion? --------------Solutions------------- You should check out Jazzy its used in s

  • Java: How to check if object is null? 2010-01-09

    I am creating an application which retrieves images from the web. In case the image cannot be retrieved another local image should be used. While trying to execute the following lines: Drawable drawable = Common.getDrawableFromUrl(this, product.getMa

  • Java substring check 2010-02-22

    I have a String2. I want to check whether String2 exists in String1. String1's length can be less or greater or equal than String2. Also String2 can be null or empty sometimes. How can I check this in my Java code? --------------Solutions------------

  • How to enable java syntax check in eclipse 3.5? 2010-08-17

    Because I installed a plugin, the java syntax check function is disabled. Does anyone know where I could enable this? such as: in Window > Preferences. Thanks Joseph --------------Solutions------------- Check the nature of your project: if java is

  • Java self-checking program (self-checksuming) 2010-12-29

    I have to do a little java self-checking programm (self-checksum). here my code sample public class tamper { public static int checksum_self () throws Exception { File file = new File ("tamper.class"); FileInputStream fr = new FileInputStream (file);

  • what is the best way to check email cc field for incorrect email addresses in java 2011-10-07

    What is the best way to check the cc field in an email for correct addresses? For example if I have cc: [email protected];[email protected];asdfj How can I detect the asdfj as an invalid address? I'm using java. The best way I can think of is using a stringto

  • JOrtho (Java Orthography Checker) 2011-10-12

    I'm new to JOrtho (Java Orthography Checker) project, wanna ask u how to use SpellChecker in the right way ? : for example, how to add User dictionary ? how to set new dictionaries ? if i use Tokenizer, what to sent to itws constructor ? I used this

  • Java: Check if next "field" in array exists 2011-03-09

    Ive made this: if( tal[i+1] ){ if( tal[i] == tal[i+1]){ match=true; } } But it doesnt seem to work. I want to check whether the field next to the current (i) exists, in the array tal[]. How can i fix this? --------------Solutions------------- If by "

  • Java: checking if Comparable is not null returns NullPointerException 2011-06-05

    I have a big problem with this code and I have no idea how to cause it: while(tree.find(indexreg)!=null){ //do stuff } For some reason, comparing tree.find(indexreg) with null causes a NullPointerException. Since this is a college project I have to u

  • java - TCP - checking for data through functions 2011-07-25

    i am trying to periodically check for objects via a function in a tcp client. i am able to successfully receive the object if i check for it in the function that makes the connection to the server, but if i attempt the same read using gClient.getUpda

  • Java: How to check if a Field is of type java.util.Collection 2011-12-07

    I have a utility method that goes through various classes and recursively retrieves the fields. I want to check if that field is a Collection. Here is some sample code: void myMethod(Class<?> classToCheck) Field[] fields = classToCheck.getDecla

  • A cool algorithm to check a Sudoku field? 2008-11-14

    Does anyone know a simple algorithm to check if a Sudoku-Configuration is valid? The simplest algorithm I came up with is (for a board of size n) in Pseudocode for each row for each number k in 1..n if k is not in the row (using another for-loop) ret

  • What are the pros and cons for different methods of checking a Collection for a null before adding to a Set? 2009-02-27

    This is a follow up question to "Is there a basic Java Set implementation that does not permit nulls?". (thank you to all of those who helped with the answer) It seems that the way to do this, since Sun didn't provide something simple like this OOTB,

Copyright (C), All Rights Reserved.

processed in 0.092 (s). 11 q(s)