Java enum 對枚舉元素的賦值和取值方式
更新時(shí)間:2024年05月16日 09:40:31 作者:AdamShyly
這篇文章主要介紹了Java enum 對枚舉元素的賦值和取值方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
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方法即可對枚舉元素進(jìn)行賦值和取值
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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java實(shí)現(xiàn)一個(gè)接口調(diào)取另一個(gè)接口(接口一調(diào)取接口二)
這篇文章主要介紹了java實(shí)現(xiàn)一個(gè)接口調(diào)取另一個(gè)接口(接口一調(diào)取接口二),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09maven項(xiàng)目下solr和spring的整合配置詳解
這篇文章主要介紹了maven項(xiàng)目下solr和spring的整合配置詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11Java死鎖代碼實(shí)例及產(chǎn)生死鎖必備的四個(gè)條件
這篇文章主要介紹了Java死鎖代碼實(shí)例及產(chǎn)生死鎖必備的四個(gè)條件,Java 發(fā)生死鎖的根本原因是,在申請鎖時(shí)發(fā)生了交叉閉環(huán)申請,synchronized在開發(fā)中最好不要嵌套使用,容易導(dǎo)致死鎖,需要的朋友可以參考下2024-01-01解決IDEA使用maven創(chuàng)建Web項(xiàng)目,出現(xiàn)500錯(cuò)誤的問題
本文主要介紹了在使用Maven創(chuàng)建項(xiàng)目并導(dǎo)入依賴寫完測試代碼后運(yùn)行出現(xiàn)500錯(cuò)誤的解決步驟,這種問題的根本原因是Tomcat啟動后缺少某些支持的jar包,導(dǎo)致運(yùn)行出錯(cuò),解決方法是在項(xiàng)目結(jié)構(gòu)中找到Artifacts,點(diǎn)擊要編輯的項(xiàng)目2024-10-10對dbunit進(jìn)行mybatis DAO層Excel單元測試(必看篇)
下面小編就為大家?guī)硪黄獙bunit進(jìn)行mybatis DAO層Excel單元測試(必看篇)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05