开发者

How can Groovy Beans standard constructors deal with null values?

I am trying to build a microsimulation mo开发者_JAVA技巧del with Groovy, but I am stuck with a problem that I traced back to Groovy’s handling of null values in Groovy Bean constructors.

In short, the constructor method that Groovy offers

new Person(nrLegs:calculationResult1, nrArms:calculationResult2)

throws an IllegalArgumentException if one of the calculation results is null, which is how I thought missing survey data would be best represented.

This is what seems strange to me: If I define a variable double age; without value, it is set to null, obviously.

double testDouble;
assert testDouble == null; // no Problem

If I do the same with Groovy beans, it has a value of 0.0, e.g:

class Person {
double age;
int nrLegs, nrArms;
}

then

Person testPerson = new Person(nrArms:calculationResult1) 
assert testPerson.age == null; // Assertion failed. testPerson.age == 0.0

Furthermore, I cannot set properties to null using the Groovy syntax:

Person testPerson = new Person(nrArms:calculationResult1) 
testPerson.age = null; // IllegalArgumentException

This seems to be exactly the same problem as above.

Why would Groovy forbid me to assign null values?

Thanks for your help!

Edit: for reference, here are the entire Person class and the StackTrace.


The problem is that you're trying to assign null to a bean property of int type.

int is a primitive type. It's not an object, and so is not nullable : it has to have a value. These are the same rules as for Java - the primitive types are int, float, boolean, double, char... . On object creation, a primitive property is initialized to 0, 0.0, false, etc.

If you need to represent 'no data', then it's probably best to edit the class definition so that the bean property uses the corresponding object wrapper type - in this caseInteger - which can then be set to null.

If you're unable to edit the class, then common work arounds are to use some kind of marker value - e.g. -1, or Integer.MIN_VALUE, or somesuch. But then logic that manipulates the Person class needs to understand the significance of the marker value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜