开发者

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, use is or has as the prefix for the method name. For example, use isOverdrawn or hasCreditLeft for methods that return true or false values. Avoid the use of the word not in the boolean method name, use the ! operator instead. For example, use !isOverdrawn instead of isNotOverdrawn.

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 condition V about an object should be named isV. An example is the method isInterrupted of class Thread.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜