Is a boolean property name prefixed by “is” still a valid Java Bean?

时间秒杀一切 提交于 2019-12-05 01:52:56

AFAIK, the naming pattern of fields is not part of the JavaBeans specification.

The JavaBeans Specification specifies (among others) the "properties" concept.

The properties of a class are identified by the methods (named after a certain pattern) of a class.

The fields are irrelevant. In fact, there doesn't even have to be a field for a property.

That said, it's still a good practice to name the fields after the property names. The chance is greater that tools which need to access the fields as well (e.g. refactoring support in IDEs) will handle the fields correctly.

Having a property named isXXX and a getter being isXXX instead of isIsXXX: is it a valid Java Bean definition?

No, a getter for a property isXXX requires isIsXXX() (for boolean) or getIsXXX().

But again it's the other way around.

If you have a method:

boolean isXyz()

then you have a readable property xyz.

If you have a method

boolean isIsXyz()

then you have a readable property isXyz.

For more information have a look at the Introspector class, the tutorial or the JavaBeans Specification:

http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html

http://www.oracle.com/technetwork/java/javase/tech/index-jsp-138795.html

Petr Shypila
private boolean certified;

public boolean isCertified() {
    return certified;
}

public void setCertified(boolean certified) {
    this.certified = certified;
}

It's ok. More info about variables names you can look on oracle.docs

It doesn't really matter what your private fields are called; that's why your setters and getters are there.

Since properties of Java Beans are usually just defined by their getter and setter methods (and the actual, most probably private, member variable is ignored for that purpose), yes, that is perfectly fine. Although I would still call the boolean member just certified, but that's a matter of style/taste.

When you generate setters/getters for boolean variable from IDE (Eclipse in many case), this is the standard way in which the setters and getters are created. It is a perfect valid Java bean definition. Infact when you use frameworks like JSF where values are passed using setters/getters, defining boolean variable and using the generated setter/getter becomes sort of mandatory.

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