Why isn't “has”… the beginning of a valid JavaBean method signature? [closed]

我的梦境 提交于 2019-12-05 03:35:49

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:

  1. ...
  2. Properties can be accessed programmatically by other components calling their getter and setter methods (see Section 7.1 below).
  3. ...

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!