关于属性命名你应该注意的点

141 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第30天,点击查看详情

对于bean的属性想必大家都很熟悉,一般都是通过get、set方法进行封装,然后暴露给外界调用。但是在给属性命名时还是除去命名规范有两点需要注意的,以下两点在前端传值的时候会特别容易出错

1、Boolean 类型的字段不能以is开头 Boolean 类型在生成get和set方法时和别的类型不太一样,Boolean的get方法是isXXX、或getXXX或者把is去掉getXXX,在生成set方法时会把变量名前的is去掉,然后在生成setXXX方法,比如isDeleted字段,get方法就是IsDeleted或者getIsDeleted、或者getDeleted,而set方法是setIsDeleted或者setDeleted。

2、属性名称首字母不能大写 在生成get和set方法时就是把首字母大写,然后加上get和set,也就是说get和set后面的字段才是真正的属性,这样前端传来的值也很可能接收不到。

下面通过反射来说明get和set后面的字段才是真正的属性 UserEntity.java

//@Data
public class UserEntity {
    private Boolean isDeleted;

    private String Username;

    private String password;

    public Boolean getDeleted() {
        return isDeleted;
    }

    public void setDeleted(Boolean deleted) {
        isDeleted = deleted;
    }

    public String getUsername() {
        return Username;
    }

    public void setUsername(String username) {
        Username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
}

get、set方法是通过idea生成的

PropertyTest.java

public class PropertyTest {
    public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        UserEntity userEntity1 = new UserEntity();

        Class<? extends UserEntity> aClass = userEntity1.getClass();
        BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor != null) {
                String displayName = propertyDescriptor.getDisplayName(); // 属性名称
                if (!"class".equals(displayName)) {
                    Method readMethod = propertyDescriptor.getReadMethod();  // get 方法
                    Method writeMethod = propertyDescriptor.getWriteMethod(); // set方法
                    System.out.println("属性名:"+displayName);
                    if (readMethod != null) {
                        System.out.println("get方法:"+ readMethod.getName()+","+readMethod.invoke(userEntity1));
                    }
                    if (writeMethod != null) {
                        System.out.println("set方法="+writeMethod.getName());
                    }
                }
            }
        }
    }
}

结果:

属性名:deleted
get方法:getDeleted
set方法=setDeleted
属性名:password
get方法:getPassword
set方法=setPassword
属性名:username
get方法:getUsername
set方法=setUsername

结果是不是UserEntity里面的属性不一样,在UserEntity里deleted是isDeleted,username是Username。所以说get和set方法之后的才是真正的属性,get和方法生成的规则不一样,前端传值过来的时候就有很大可能接收不到值,所以属性命名的时候要特别注意。

PropertyDescriptor 是一个属性描述器,可以获取一个bean的属性、读方法和写方法。

能力有限,水平一般,如有错误,请多指出。