Valid JavaBeans names for boolean getter methods

后端 未结 3 544
不思量自难忘°
不思量自难忘° 2020-12-01 04:28

I know most variable names will work with \"is\", such as isBlue(), but is \"has\" also a valid prefix, like hasProperty()?

3条回答
  •  时光取名叫无心
    2020-12-01 04:56

    Jon Skeet noted that according to the specification it is not valid. Also, canX, shouldX, and the likes are not valid. Which is rather unfortunate. Here is a way to check whether a given property has a valid getter:

    BeanInfo info = Introspector.getBeanInfo(Item.class);
    Item itm = new Item();
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        System.out.println(pd.getName() + " : " + pd.getReadMethod());
    }
    

    The class Item should be a javabean with a foo property, and a getter. If the read method is null, it means there is no valid getter defined according to the javabeans spec.

提交回复
热议问题