There is an option in Eclipse (Preferences -> Java->Code Style)
It allows "is" Prefix for getters if the return is boolean.
My question why does it not do the prefixing if the return is the wrapper class (Boolean) ?
There is an option in Eclipse (Preferences -> Java->Code Style)
It allows "is" Prefix for getters if the return is boolean.
My question why does it not do the prefixing if the return is the wrapper class (Boolean) ?
This is simply because per the java beans specification/convention/implementation is prefix is only intended for primitive objects.
You can take a look at the PropertyDescriptor class source (getRealMethod):
if (readMethodName == null) {
Class type = getPropertyType0();
if (type == boolean.class || type == null) {
readMethodName = "is" + getBaseName();
} else {
readMethodName = "get" + getBaseName();
}
}
So eclipse is only conforming to this.
Edit: now why the property descriptor is made this way is another question, probably Java folks decided that the possibility of null return type and the "is" prefix may be misleading.
boolean is a primitive type and Boolean is an object. An object has other properties aside from just being true or false. So perhaps this is the reason why they designed it for the primitive type only.
If there's a getter named isActive, you would want it to return either true or false, not null or anything else.
In primitive type boolean
, only true
and false
are possible. But if you use Object type Boolean
, null
is also accepted. Normally is not suitable in such a scenario.
public class MyClass{
private boolean status;
private Boolean sts;
public boolean isStatus(){
return status;
}
public Boolean getSts(){
return sts;
}
// setters
}
When we call isStatus
result definitely true or false. It is make sense. But isSts
can return null
. This is some what not logical. This may be the reason to use get for Object
type.
When the isFoo/setFoo special case of the getter and setter naming convention for properties was established, Boolean was considered more closely related to all other object types than to the boolean primitive type; the result of getFoo can be null, the result of isFoo cannot.
Now that the Java language has automatic boxing and unboxing of primitive types, there's a greater chance of Boolean variables interacting with boolean properties, but Boolean properties remain unusual because setting them to null remains a strange and usually troublesome use case.