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; } }
通過定義構(gòu)造方法和get方法即可對枚舉元素進行賦值和取值
if (Trade.withdraw.getType().equals("1")) { // true }
動態(tài)賦值給枚舉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; //通過靜態(tài)內(nèi)部類的方式注入到bean,并 賦值到枚舉中。 @PostConstruct public void postConstruct() { for (Level level : EnumSet.allOf(Level.class)) { level.setMessageSource(messageSource); } } }
在messages.properties中加入測試信息
level.LOW=低 level.MEDIUM=中 level.HIGH=高
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java實現(xiàn)一個接口調(diào)取另一個接口(接口一調(diào)取接口二)
這篇文章主要介紹了java實現(xiàn)一個接口調(diào)取另一個接口(接口一調(diào)取接口二),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09解決IDEA使用maven創(chuàng)建Web項目,出現(xiàn)500錯誤的問題
本文主要介紹了在使用Maven創(chuàng)建項目并導(dǎo)入依賴寫完測試代碼后運行出現(xiàn)500錯誤的解決步驟,這種問題的根本原因是Tomcat啟動后缺少某些支持的jar包,導(dǎo)致運行出錯,解決方法是在項目結(jié)構(gòu)中找到Artifacts,點擊要編輯的項目2024-10-10對dbunit進行mybatis DAO層Excel單元測試(必看篇)
下面小編就為大家?guī)硪黄獙bunit進行mybatis DAO層Excel單元測試(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05