成员变量命名为什么不建议用isXXX

参考答案

2020.04.22发布的《阿里开发规范泰山版》编程规约,关于命名风格的第8条规定:

【强制】POJO 类中的任何布尔类型的变量,都不要加 is 前缀,否则部分框架解析会引起序列化错误。

使用快捷键进行生成getset方法时,它会把“is”给吃掉,问题就出在private boolean isAtAll;这个字段上,使用fastjson序列化之后,该属性实际转化为了:“atAll”: true。

为什么序列化之后,is被吃掉了呢?

带着这个问题,追踪下fastjson的源码,发现在序列化的时候,其使用的是属性的getter方法名,而isAtAll字段自动生成的getter、setter为:

  1. public boolean isAtAll() {
  2. return isAtAll;
  3. }
  4.  
  5. public void setAtAll(boolean atAll) {
  6. isAtAll = atAll;
  7. }

对应的fastjson中对方法名的处理在com.alibaba.fastjson.util.TypeUtils.computeGetters中,源码摘录:

  1. if(methodName.startsWith("is")){
  2. if(methodName.length() < 3){
  3. continue;
  4. }
  5. if(method.getReturnType() != Boolean.TYPE
  6. && method.getReturnType() != Boolean.class){
  7. continue;
  8. }
  9. String propertyName;
  10. Field field = null;
  11. if(Character.isUpperCase(c2)){
  12. if(compatibleWithJavaBean){
  13. propertyName = decapitalize(methodName.substring(2));
  14. } else{
  15. propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3);
  16. }
  17. propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 2);
  18. }

对于is开头的方法,fastjson先把第3个字符截取出来,如果该字符是大写,就转换为小写,并且拼装剩余的方法名组成属性名。

例如:

isAtAll方法拼装出来的属性名就是atAll,把is给吃掉了。

解决方法是:不要用isxxx命名。

以上,是Java面试题【成员变量命名为什么不建议用isXXX】的参考答案。

输出,是最好的学习方法

欢迎在评论区留下你的问题、笔记或知识点补充~

—end—

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧