Java enum 对枚举元素的赋值和取值方式
作者:AdamShyly
这篇文章主要介绍了Java enum 对枚举元素的赋值和取值方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Java enum对枚举元素的赋值和取值
package edu.fjnu501.bankenum;
public enum Trade {
save("0"), withdraw("1");
private String type;
Trade(String s) {
type = s;
}
public String getType() {
return this.type;
}
}通过定义构造方法和get方法即可对枚举元素进行赋值和取值
if (Trade.withdraw.getType().equals("1")) {
// true
}动态赋值给枚举enum
枚举类 Level.java
public enum Level {
LOW("0", "level.LOW"),
MEDIUM("1", "level.MEDIUM"),
HIGH("2", "level.HIGH");
private String value;
private String description;
private Level(String value, String description) {
this.value = value;
this.description = description;
}
public String getValue() {
return this.value;
}
public String getDescription() {
return messageSource.getMessage(description, null, description, null);
}
//spring 框架的类
private MessageSource messageSource;
public Level setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
return this;
}配置类
@Component
public class EnumValuesInjectionService {
@Autowired
private MessageSource messageSource;
//通过静态内部类的方式注入到bean,并 赋值到枚举中。
@PostConstruct
public void postConstruct() {
for (Level level : EnumSet.allOf(Level.class)) {
level.setMessageSource(messageSource);
}
}
}在messages.properties中加入测试信息
level.LOW=低 level.MEDIUM=中 level.HIGH=高
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
