17

我刚刚在一个 Webapp 中有点意外,我在 .jsp 页面中使用了 EL。

我添加了一个布尔属性并摸不着头脑,因为我将布尔值命名为“isDynamic”,所以我可以这样写:

<c:if test="${page.isDynamic}">
   ...
</c:if>

我发现它比以下内容更容易阅读:

<c:if test="${page.dynamic}">
   ...
</c:if>

但是 .jsp 无法编译,出现错误:

javax.el.PropertyNotFoundException: Property 'isDynamic' not found on type com...

我发现我的 IDE(我花了一些时间才注意到它),在生成 getter 时,生成了一个名为:

isDynamic()

代替:

getIsDynamic()

一旦我用 getIsDynamic() 手动替换isDynamic() 一切正常。

所以我在这里有两个问题:

  1. 以“is”开头的布尔属性名称是否不好?

  2. 不管它坏与否,IntelliJ 不是在这里通过自动生成一个名为isDynamic而不是getIsDynamic的方法犯了错误吗?

4

4 回答 4

29
于 2010-05-31T17:32:57.627 回答
11

isDynamic() is normally the way to go as a boolean getter.

public boolean isDynamic() {
  return dynamic;
}

in your template you can use:

<c:if test="${dynamic}">
 ...
</c:if>
于 2010-05-31T17:33:36.723 回答
1

更典型的做法是将属性命名为不带“is”,让访问者有“is”。不过,您当然可以更改您的 IDE 生成的内容,如果这对您来说更清楚,可以让“getIsDynamic()”成为访问器。

于 2010-05-31T17:31:09.583 回答
1

Since in Java you don't have clash between variable names and method it would say that it's ok to have an isDynamic() method that returns if isDynamic is true. Or at least this is good if the "dinamicity" is actually a real attribute of the object and not just a boolean value that you need.

For example verbose is a boolean value that is usually not an attribute of an object, so having a isVerbose() method would be a bad idea (unless it's a Console class).

Having a boolean called isDynamic is a good expressive idea. It suggests you that the variable is a bool without any additional effort.

于 2010-05-31T17:33:21.423 回答