Java enum 对枚举元素的赋值和取值方式
更新时间:2024年05月16日 09:40:31 作者: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=高
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章
Java中SpringBoot的@Transactional原理
这篇文章主要介绍了Java中SpringBoot的@Transactional原理,面向元数据遍历已经成为越来越多开发者的偏好,因此原理从Springboot的EnableTransactionManagement注解说起,需要的朋友可以参考下2023-07-07
SpringBoot使用MapStruct生成映射代码的示例详解
MapStruct 是一个用于 Java 的代码生成器,专门用于生成类型安全的 bean 映射代码,它通过注解处理器在编译时生成映射代码,从而避免了运行时的性能开销和潜在的错误,本文给大家介绍了SpringBoot使用MapStruct生成映射代码的示例,需要的朋友可以参考下2024-11-11


最新评论