简体   繁体   中英

Boolean Getter and Setter using eclipse

I am wondering why eclipse produces the following getter and setter if i used the following boolean:

boolean isLifeTimeMember

图片

The getter should be isIsLifeTimeMember() and not isLifeTimeMember()

I think it affected calling the variable isLifeTimeMember in JSP. because it will look at JSP and map it to isIsLifeTimeMember() getter method.

Error will result because there is no isIsLifeTimeMember() method but the getter generated by eclipse is isLifeTimeMember()

Thank you.

Eclipse name generation rules are that boolean getters should start with is . If the variable name already starts with is , then it thinks that no additional prefix is necessary.

Eclipse has a setting that controls the use of is for generated boolean getters. Open up Preferences and navigate to Java > Code Style . There you can uncheck the option "Use 'is' prefix for getters that return boolean". Eclipse-generated boolean getters will then start with "get", just like all the others.

Java has no problem, by the way, in having a field and a method with the same name.

However, having property names that start with "is" will probably cause problems with jsp. As described in this thread , it's better to avoid property names that read like questions (isLifeTimeMember) and instead just use the property itself as the property name (lifeTimeMember).

Code Example:

boolean lifeTimeMember;

public boolean isLifeTimeMember() {
   return lifeTimeMember;
}

public void setLifeTimeMember(boolean lifeTimeMember) {
   this.lifeTimeMember = lifeTimeMember;
}

And in JSP if you need to use this variable simply use variable name "lifeTimeMember".

In case of boolean variable, eclipse prepends is to the variable name to form the getter name. Ie If variable is boolean present; then the gemerated getter would be named isPresent();

Its not advisable to have an is in the variable name.

If the variable name is ispresent , on jsp you will lookup by variable name ispresent which in turn looks up for its getter, its an boolean so it assumes getter would be isispresemt(); which was not there as the getter setter generator in eclipse does not add an is in case that already existe in variable name.

thus an exception could not find the field ispresent is expected to be thrown

having an is in field name , can cause problems, avoid using them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM