Why is there no "has" ... the beginning of a valid JavaBean method signature?

The signature of JavaBeans methods must follow certain conventions, such as set ... / get ... and the like. They have an agreement for ... for example, isEven() may be a method for an integer class to check for Boolean. But then I wonder why not ... is also a legal identifier, as it makes sense to verify that something has, for example. hasCar() for the Person class or similar.

Do you understand my question? What do you think?

+8
java javabeans
source share
3 answers

Well, the general convention is to use get... and set... , and thus is... is just an exception for booleans. For is... convention is easy: you need to return a boolean, you can skip the getter, and the corresponding typesetter will also accept the boolean parameter.

Aligning for has... will be more complicated: has... will return a boolean, but you still need getter and setter, which deal with different types. Thus, has... does not replace get... unlike is... , and since this part of the JavaBeans convention, as a rule, applies only to hasters and setters, has... does not fit there.

From the JavaBeans specification:

Properties are discrete, named Java Bean attributes ...

Properties are displayed in several ways:

  • ...
  • Access to properties is possible programmatically with the help of other components that call them and configuration methods (see section 7.1 below).
  • ...

Any property accessed using has... will not be permanent and will not be accessible by its getter method.

Example: if a person has a car property, you must have the getCar() accessory. hasCar() will not be an accessory because the hasCar derived property needs an accessor named getHasCar() or isHasCar() . If has was an access prefix, the property has the inconsistent name car .

+5
source share

get/set and is/set for a boolean type is just a convention. I agree that sometimes it is better to read getter hasSomething . For example hasChildren() . But let go ahead and say it's okay to call the canWrite() or willFly() or providesResult() method, etc. And you can use such names, but these names do not conform to the java bean standard and therefore will not be recognized as getters using java bean frameworks.

Java Beans were invented many years ago. It would probably be nice to define the annotations @Setter and @Getter . If these annotations become common, all java bean frameworks can support them, and programmers can call getters as they like, but mark them with the @Getter annotation. But such annotations are no longer supported, so we recommend that you only follow existing naming conventions.

+1
source share

I do not think this is a bad question! I also thought about it and found that people use it as you are going to use it . It's just that most libraries (like the one you use) don't have one.

I agree that it should be valid for logical properties.

0
source share

All Articles