Valid JavaBeans names for boolean getter methods

JavaBooleanNaming ConventionsJavabeans

Java Problem Overview


I know most variable names will work with "is", such as isBlue(), but is "has" also a valid prefix, like hasProperty()?

Java Solutions


Solution 1 - Java

According to the JavaBeans specification section 8.3.2:

> Boolean properties
> In addition, for > boolean properties, we allow a getter > method to match the pattern:

public boolean is<PropertyName>();

> This > "isPropertyName" method may be > provided instead of a > "get<PropertyName>" method, or it may > be provided in addition to a > "get<PropertyName>" method. In either > case, if the is<PropertyName> method > is present for a boolean property then > we will use the "is<PropertyName>" > method to read the property value. An > example boolean property might be:

>

> public boolean isMarsupial();
> public void setMarsupial(boolean m);

In other words, unless something has changed since then, has isn't a valid prefix I'm afraid :(

It's possible that some tools and libraries will recognise such properties anyway, but it's not a good idea to rely on it.

Solution 2 - Java

Jon Skeet noted that according to the specification it is not valid. Also, canX, shouldX, and the likes are not valid. Which is rather unfortunate. Here is a way to check whether a given property has a valid getter:

BeanInfo info = Introspector.getBeanInfo(Item.class);
Item itm = new Item();
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
    System.out.println(pd.getName() + " : " + pd.getReadMethod());
}

The class Item should be a javabean with a foo property, and a getter. If the read method is null, it means there is no valid getter defined according to the javabeans spec.

Solution 3 - Java

This is somewhat subjective, but yes, I would say "has" is a perfectly valid prefix for a Boolean property.

edit the question, as asked, did not mention the javabeans specification and so my answer did not address that aspect of the question. Hence the answer above.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobertView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow
Solution 3 - JavaRyan GuillView Answer on Stackoverflow