枚举类在项目中的实战

来源:互联网 发布:域名被劫持了怎么处理 编辑:程序博客网 时间:2024/05/16 10:54

在项目中,多少会有这样的功能,如添加用户的时候,我们要为用户提供用户类型的选择。

例如:图书管理系统中,添加用户模块有这么几个用户类型:超级管理员,图书管理员,进货管理员,销售管理员,库存管理员

那么我们如何在程序中去区分它们呢。

我们则需要用到枚举

例如图书管理系统用户模块的用户枚举类代码:

public enum UserTypeEnum{

ADMIN(1,"超级管理员"),BOOK(2,"图书管理员"),IN(3,"进货管理员"),OUT(4,"销售管理员"),STOCK(5,"库存管理员");

private int type;

private String name;

private UserTypeEnum(int type,String name){

this.name=name;

this.type=type;

}

public int gettype(){

return type;
}

pubilc String getname(){
return name;

}

public static String getNameByType(int Type){

for(UserTypeEnum userType:UserTypeEnum.Valus()){

if(userType.gettype==Type){

return name;
}
         }

throw new IllegalArgumentException("No such type \"" + type
+ "\" in UserTypeEnum");
}


public static int getTypeByName(String name) {
for (UserTypeEnum userType : UserTypeEnum.values()) {
if (userType.getName().equals(name)) {
return userType.getType();
}
}
throw new IllegalArgumentException("No such name \"" + name
+ "\" in UserTypeEnum");
}

}

枚举类写好了 我们该如何去使用它呢

例如 在添加用户模块中:AddJpanel中有comboBox组件,通过UserVO传递的Type是int型。我们应该如何将其转换成String型呢

for(UserTypeEnum:usertype:UserTypeEnum.valus()){

combType.addItem(userType.getName());//遍历每一个Type,一个个添加到组件中
}

这样我们在选择的时候看到的就是字符串了,在返回给UserVo保存到数据库中时,我们再转换回type即可




1 0
原创粉丝点击