java 枚举转换_java 中枚举类型,整型,字符串之间转换

先说说简单的枚举类型,与字符串,整型之间的转换。

可以理解为,枚举,就是一个简单的数组

public enum Weather {

winter,

spring,

summer,

fall

}

public class EnumDemo {

public static void main(String[] args) {

//System.out.println();

//枚举转换整型

int winter = Weather.winter.ordinal();

System.out.println(winter);

System.out.println(Weather.spring.ordinal());

System.out.println(Weather.summer.ordinal());

System.out.println(Weather.fall.ordinal());

//枚举转换字符串。

String win = Weather.winter.toString();

String win2 = Weather.winter.name();

System.out.println(win);

System.out.println(win2);

//字符转换枚举

Weather weather = Weather.valueOf("spring");

System.out.println(weather);

//整型转换枚举

int winter0 = 2;

Weather weather2 = Weather.values()[winter0];

System.out.println(weather2);

}

}

带参数枚举

public enum BusinessEnum {

User(1, BusinessType.USER_BUSINESS),

Order(2, BusinessType.ORDER_BUSINESS);

private int type;

private BusinessType businessType;

private BusinessEnum(int type, BusinessType businessType) {

this.type = type;

this.businessType = businessType;

}

public int getType() {

return type;

}

public void setType(int type) {

this.type = type;

}

public BusinessType getBusinessType() {

return businessType;

}

public void setBusinessType(BusinessType businessType) {

this.businessType = businessType;

}

public static BusinessEnum getEnumByType(int type) {

for (BusinessEnum bt : values()) {

if (bt.type == type) {

return bt;

}

}

return null;

}

}

public enum BusinessType {

USER_BUSINESS,

ORDER_BUSINESS

}

demo:

public class BusinessEnumDemo {

public static void main(String[] args) {

//System.out.println();

BusinessEnum business1 = BusinessEnum.getEnumByType(1);

BusinessEnum business2 = BusinessEnum.getEnumByType(2);

System.out.println(business1);

System.out.println(business2);

BusinessType type1 = business1.getBusinessType();

BusinessType type2 = business2.getBusinessType();

System.out.println(type1);

System.out.println(type2);

}

}

输出:

User

Order

USER_BUSINESS

ORDER_BUSINESS

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页