Android中为什么有些变量会以m开头?
程序员文章站
2022-07-13 21:53:19
...
private String mTitleText;
- 1
为什么变量名非得以 ‘m’ 开头呢?像上面这样。而不是这样呢?
private String titleText;
- 1
这个疑问终于有一天我找到了答案。
Follow Field Naming Conventions
Non-public, non-static field names start with m.
Static field names start with s.
Other fields start with a lower case letter.
Public static final fields (constants) are
ALL_CAPS_WITH_UNDERSCORES.
也就是说:
- 非公有、非静态域的变量以m开头(其实就是protected和private成员变量)
- 静态变量以s开头
- 其它变量以小写字母开头
- Public static final变量(常量)以下划线连接全大写ALL_CAPS_WITH_UNDERSCORES
举个例子:
public class MyClass {
public static final int SOME_CONSTANT = 42;
public int publicField;
private static MyClass sSingleton;
int mPackagePrivate;
private int mPrivate;
protected int mProtected;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
好,知道了这些规则,于是我定义了这样一个实体类:
public class User {
private String mName;
private String mPassword;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
下面要生成 getter 和 setter 方法,于是,
按下 Alt + Insert 键 选择 Getter and Setter .
生成下面的代码:
public class User {
private String mName;
private String mPassword;
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmPassword() {
return mPassword;
}
public void setmPassword(String mPassword) {
this.mPassword = mPassword;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
发现 Getter and Setter 方法多了一个 m 。
这样确实很难看,有没有办法让Android Studio 能自动识别出前缀呢?
一张图你就明白了:
先打开这个设置页面,然后:
这样就Ok了,
现在来看下效果:
public class User {
private String mName;
private String mPassword;
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getPassword() {
return mPassword;
}
public void setPassword(String password) {
mPassword = password;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
上一篇: Linux学习之路-(2.vi编辑器)
下一篇: 第三次打卡笔记