问题
I have a variable called
List<String> names;
if i have a method like
Iterator getNames()
{
return names.iterator();
}
Is it technically still a getter method because i changed it to Iterator?
回答1:
Even though the JDK allows this, its not a good idea to do it.
For one, there are conventions based off of the naming of your methods, that have some dependencies on them.
JavaBean objects use getters and setters to set bean properties. If they disobey the convention, the program will fail. See JavaBeans spec, section 8.3.1
JSON objects - the JSONObject class uses the accessor methods in the constructor. See: http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject(java.lang.Object)
Some JPA implementations will incorrectly process your entity classes if they have multiple getters with the same name but different return types.
I bet there are more dependencies, but even if these don't apply to your solution, it's still wise to follow the convention for the sake of readability. You don't want any other developer cursing you sometime in the future for breaking the standards :)
回答2:
It seems like a bad idea to me from a design point of view.
I would simply have a getter public List<String> getNames()
.
For "safe publishing", you should consider returning a copy of the list in the implementation:
public List<String> getNames() {
return new ArrayList<String>(names);
}
回答3:
If you class is going to be introspected by some bean tool, getNames() should return names. For clarity, call it what it is:
getNamesIterator();
回答4:
You are thinking the otherway around. A method of the form getXxx is a getter. Java conventions don't imply that you must have a field named xxx. This is your class business and encapsulation provides just : the abilit to hide your data struxtures to other classes.
Sorry for typo, mobile..
来源:https://stackoverflow.com/questions/9747291/does-a-getter-with-a-different-return-type-qualify-as-a-getter