The JavaBeans methods' signature's has to follow certain conventions such as set.../get... and such. They have a convention for is...for instance isEven() could be a method for an Integer class to test a boolean. But then I wonder why not has... is also a legal identifier since it makes sense to me to test what something has e.g. hasCar() for a Person class or likewise.
Do you understand my question? What do you think?
Well, the general convention is to use get... and set... and thus is... is just an exception for booleans. For is... the convention is easy: you need to return a boolean, can skip the getter and the corresponding setter will take a boolean parameter as well.
A convention for has... would be more difficult: has... would return a boolean but you'd still need a getter and setter which deal with different types. Thus has... is no replacement for get... as opposed to is... and since that part of the JavaBeans convention normally only is about getters and setters has... doesn't fit in there.
From the JavaBeans spec:
Properties are discrete, named attributes of a Java Bean...
Properties show up in a number of ways:
- ...
- Properties can be accessed programmatically by other components calling their getter and setter methods (see Section 7.1 below).
- ...
Any property being accessed using has... would not be persistent nor be accessed by its getter method.
Example: if a person has a car property, you'd expect to have a getCar() accessor. hasCar() wouldn't be an accessor since the derived property hasCar would need an accessor named getHasCar() or isHasCar(). If has was an accessor prefix, the property would have the conflicting name car.
get/set and is/set for boolean type is just the convention. I agree that sometimes it is more readable to call getter hasSomething. For example hasChildren(). But let's go forward and say that it is fine to call method canWrite() or willFly() or providesResult() etc. And you can use such names but these names are not following java bean convention and therefore will not be recognized as getters by java bean frameworks.
Java Beans were invented a lot of years ago. Probably it is not a bad idea to define annotations @Setter and @Getter. If these annotations become common all java bean frameworks could support them and programmers will be able to call getters as they want but mark them with annotation @Getter. But such annotations are not supported now, so the only advise is to follow existing naming conventions.
I do not think this is a bad question at all! I thought about that too and found that people do use it like you intend to use it. It's just that most libraries (like the one you propably use) don't.
I agree that it should be valid for boolean properties.
来源:https://stackoverflow.com/questions/11934866/why-isnt-has-the-beginning-of-a-valid-javabean-method-signature