I am working with some code where the user sends in an object which can have upwards of 100 values to it. (Let's use a car for example).
updateDatabasePrep(carObject);
The car object COULD have things like name, milage, vin, color, etc... but say I only set the color and then pass the object.
In my method:
public void updateDatabasePrep(Car carObject){
NewObject myObject = newObject(); //Initialized, but empty
String x1 = carObject.getMilage();
String x2 = carObject.getColor();
String x3 = carObject.getName();
//These will hold null values no problem
//Once the rest of the data has been collected:
//These, however, will error out when I try to set the null values.
myObject.setMilage(x1);
myObject.setColor(x2);
myObject.setName(x3);
}
It uses accessor methods which will pull the data from the passed object and then tries to set said values. In the above situation, it will throw a null pointer error as the milage and name are null; only the color is not.
My goal is to update the database with ONLY the values that have been set. In this case, I COULD write a ton of if/ else or try/ catch statements for every single one, that would work, but I would prefer not to.
Is there a shorter way to do this in Java? Is there a method where you can ONLY set data if it is not-null other than if/ else, try/catch, and going through every single setter method and telling it to skip null values?
EDIT: Just to clarify, the Nullpointerexception will get thrown on when it tries to set a null value. IE
myObject.setMilage(x1);
since people we asking.