定义常量方便统一管理常量,是一种专业的表现,个人推荐使用第三种枚举定义常量
第一种:静态变量的方式
package vip.lizhilong.lambda;
/**
* Created by Jackielee on 2017
* @author: lizhilong
*/
public class GenderContents {
public static Integer BOY = 0;
public static Integer GIRL = 1;
public static Integer LADYBOY = 2;
}
第二种:接口定义常量(别人可能实现此接口,导致常量数据不安全,不推荐)
package vip.lizhilong.lambda;
public interface GenderContent {
public Integer BOY = 0;
public Integer GIRL = 1;
public Integer LADYBOY = 2;
}
package vip.lizhilong.lambda;
/**
* @author: lizhilong
* @date: 2017-11-24 10:34:10
*/
public enum GenderColumn {
BOY(0, "男"),
GIRL(1, "女"),
LADYBOY(2, "人妖");
private Integer code;
private String message;
GenderColumn(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
/**
* 根据code获取当前的枚举对象
* @param code
* @return GenderColumn
*/
public static GenderColumn of(Integer code) {
if (code == null) {
return null;
}
for (GenderColumn status : values()) {
if (status.getCode().equals(code)) {
return status;
}
}
return null;
}
}
常量获取方式:
@Test
public void contentsTest(){
// 静态变量
Integer classCode = GenderContents.BOY;
// 接口
Integer implCode = GenderContent.BOY;
// 枚举
Integer enumCode = GenderColumn.BOY.getCode();
System.out.println("classCode:" + classCode + "\n" +
"implCode:" + implCode + "\n" +
"enumCode:" + enumCode);
}
打印结果:
classCode:0
implCode:0
enumCode:0
总结:三种常量都有各自的优缺点,请谨慎使用
纯手工操作,欢迎批评指正