Can you explain the "isXxx" method names in Java?
Is there in one of the specifications any reference to methods that start with "is", while the suffix of the method's name is a pro开发者_如何学Pythonperty's name (similar to getter/setter methods of Java beans)?
For example:
public boolean isConditionTrue() {
...
...
}
private boolean conditionTrue;
Thanks!
This is a Java naming convention,
If the method returns a
boolean
value, useis
orhas
as the prefix for the method name. For example, useisOverdrawn
orhasCreditLeft
for methods that returntrue
orfalse
values. Avoid the use of the wordnot
in theboolean
method name, use the!
operator instead. For example, use!isOverdrawn
instead ofisNotOverdrawn
.
See also:
- Java Style Guide: Method Naming Convention
- Java Language Specification - Method Names
According to the Java Language Specification,
A method that tests a
boolean
conditionV
about an object should be namedisV
. An example is the methodisInterrupted
of classThread
.
is only valid for primitive boolean. Here is an excerpt from the spec:
8.3.2 Boolean properties In addition, for boolean properties, we allow a getter method to match the pattern: public boolean is(); This “is” method may be provided instead of a “get” meth- od, or it may be provided in addition to a “get” method. In either case, if the “is” method is present for a boolean property then we will use the “is” method to read the property value. An example boolean property might be: public boolean isMarsupial(); public void setMarsupial(boolean m);
Be aware of using isXxx() : Boolean
functions if you are going to use them in conjunction with things like JSTL tags (using ${object.xxx}
syntax). They won't pick it up and you have to modify it to getXxx() : Boolean
.
The is is
a prefix for accessor methods to boolean
type instance variables.
This is the convention for boolean
data types, while get/set
is the convention
for other types.
精彩评论