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

た 入场券 2023-05-21 11:54 62阅读 0赞

对于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

  1. //@Data
  2. public class UserEntity {
  3. private Boolean isDeleted;
  4. private String Username;
  5. private String password;
  6. public Boolean getDeleted() {
  7. return isDeleted;
  8. }
  9. public void setDeleted(Boolean deleted) {
  10. isDeleted = deleted;
  11. }
  12. public String getUsername() {
  13. return Username;
  14. }
  15. public void setUsername(String username) {
  16. Username = username;
  17. }
  18. public String getPassword() {
  19. return password;
  20. }
  21. public void setPassword(String password) {
  22. this.password = password;
  23. }
  24. }

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

PropertyTest.java

  1. public class PropertyTest {
  2. public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
  3. UserEntity userEntity1 = new UserEntity();
  4. Class<? extends UserEntity> aClass = userEntity1.getClass();
  5. BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
  6. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  7. for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
  8. if (propertyDescriptor != null) {
  9. String displayName = propertyDescriptor.getDisplayName(); // 属性名称
  10. if (!"class".equals(displayName)) {
  11. Method readMethod = propertyDescriptor.getReadMethod(); // get 方法
  12. Method writeMethod = propertyDescriptor.getWriteMethod(); // set方法
  13. System.out.println("属性名:"+displayName);
  14. if (readMethod != null) {
  15. System.out.println("get方法:"+ readMethod.getName()+","+readMethod.invoke(userEntity1));
  16. }
  17. if (writeMethod != null) {
  18. System.out.println("set方法="+writeMethod.getName());
  19. }
  20. }
  21. }
  22. }
  23. }
  24. }

结果:

  1. 属性名:deleted
  2. get方法:getDeleted
  3. set方法=setDeleted
  4. 属性名:password
  5. get方法:getPassword
  6. set方法=setPassword
  7. 属性名:username
  8. get方法:getUsername
  9. set方法=setUsername

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

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

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

发表评论

表情:
评论列表 (有 0 条评论,62人围观)

还没有评论,来说两句吧...

相关阅读