有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

netbeans根据命名约定返回布尔类的getter的Java名称

我注意到对于返回Boolean(而不是boolean)的getternetbeans生成带有“get”前缀的getter。例如:

private Boolean main;

public Boolean getMain(){
  return this.main;
}

这是错误的(根据命名约定)?或者“是”前缀仅用于基本类型


共 (6) 个答案

  1. # 1 楼答案

    根据OCP Oracle认证专业Java SE 8程序员II学习指南:

    以下哪项可以正确地包含在JavaBean中

    public boolean isPlaying() { return playing; }
    public boolean getPlaying() { return playing; }
    public Boolean isDancing() { return dancing; }
    

    第一行是正确的,因为它为布尔变量定义了正确的getter。 第二个示例也是正确的,因为boolean可以使用is或get第三行是 不正确,因为布尔包装应该以get开头,因为它是一个对象

  2. # 2 楼答案

    这取决于是否将包含该方法的类视为JavaBean

    如果您希望它是一个JavaBean,那么Marko Topolnik's answer是准确的

    否则就没有对错。是否使用getis(或其他)取决于合同和方法的目的。Eran的第一个评论是:

    There's no right or wrong here. I think isMain or hasMain or supportsMain (depnding on what main means) are more descriptive. I don't think it should make a different whether it's boolean or Boolean.

    你问约定是什么,我会说约定是将方法命名为描述性的,语义上尽可能准确

    要详细说明还是获取

    • 如果该方法旨在作为capital-B Boolean属性的通用访问器,使其接受值null,则使用get更有意义

    • 如果该方法旨在给出一个其他内部(如本例中的private)非空标志的状态,我认为is将是一个合适的前缀。(尽管我可能会使用boolean作为返回值,除非有一个常见的用例,例如isMain().hashCode()或类似的东西。)

  3. # 3 楼答案

    Netbeans在这里没有错-对于Boolean对象属性get是正确的。首先,属性值可以是null,在这种情况下is没有意义

    javabeans spec允许is类型boolean作为特例,没有提到Boolean。假设此特殊情况扩展到Boolean对象是无效的

  4. # 4 楼答案

    这是正确的。Boolean是原始数据类型Boolean的包装类。所以布尔值将返回object。同样的get也用于对象,就像原始数据类型一样

  5. # 5 楼答案

    这里引用了实际的JavaBeans specification document

    8.3.2 Boolean properties

    In addition, for boolean properties, we allow a getter method to match the pattern:

    public boolean is<PropertyName>();

    This is<PropertyName> method may be provided instead of a get<PropertyName> method, or it may be provided in addition to a get<PropertyName> method. In either case, if the is<PropertyName> method is present for a boolean property then we will use the is<PropertyName> method to read the property value.

    请注意,这适用于boolean而不是Boolean值。还请注意isget允许的替代,而get总是合适的

  6. # 6 楼答案

    Boolean对象上,可以应用许多方法:toStringequalsvalueOf

    你的问题没有完整的答案,这取决于用法和调用方法的人。有必要:

    public boolean isMain(){
        return this.main.booleanValue();
    }
    

    但是如果您的逻辑不能确保main可以有null值,那么get是一个很好的前缀