定义一个枚举
public enum UserRole {
STUDENT,//学生
TEACHER,//教师
ADMIN;//管理员
}
枚举的基本用法
-
values():返回所有枚举常量的数组集合
for (UserRole userRole : UserRole.values()) { System.out.println(userRole); } //打印: //STUDENT //TEACHER //ADMIN
-
nam():获取枚举常量名:
for (UserRole userRole : UserRole.values()) { System.out.println(userRole.name()); } //打印: //STUDENT //TEACHER //ADMIN
-
valueOf(String name):返回指定名称的枚举常量
System.out.println(UserRole.valueOf("ADMIN")); //打印:ADMIN
-
switch:
public void test(UserRole role){ switch (role){ case ADMIN:System.out.println("ADMIN");break; case STUDENT:System.out.println("STUDENT");break; case TEACHER:System.out.println("TEACHER");break; } }
自定义扩充
import lombok.Getter;
@Getter
public enum UserRole {
STUDENT("学生",1),
TEACHER("教师",2),
ADMIN("管理员",0);
//自定义属性
private final String roleName;
private final Integer roleCode;
//自定义构造函数
UserRole(String roleName,Integer roleCode){
this.roleName = roleName;
this.roleCode = roleCode;
}
//自定义方法
public static String getRoleNameByRoleCode(Integer roleCode){
for (UserRole role : UserRole.values()) {
if(role.getRoleCode() == roleCode)
return role.getRoleName();
}
return null;
}
}