package com.example;
import java.util.Arrays;
public enum MonthEnum {
January(1, "Jan"),
February(2, "Feb"),
March(3, "Mar"),
April(4, "Apr"),
May(5, "May"),
June(6, "Jun"),
July(7, "Jul"),
August(8, "Aug"),
September(9, "Sept"),
October(10, "Oct"),
November(11, "Nov"),
December(12, "Dec");
private final int code;
private final String name;
MonthEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
/**
* @param code
* @return
*/
public static MonthEnum getEnumByCode(int code) {
for (MonthEnum e : MonthEnum.values()) {
if (e.getCode() == code) {
return e;
}
}
return null;
}
/**
* @param name
* @return code
*/
public static int getCodeByName(String name) {
for (MonthEnum e : MonthEnum.values()) {
if (e.getName().equalsIgnoreCase ( name) ) {
return e.getCode() ;
}
}
return 0;
}
public static int valueByName(String name) {
MonthEnum e=Arrays.stream(MonthEnum.values()).filter(ec -> ec.getName().equalsIgnoreCase ( name)).findFirst().orElse(null);
if(e==null){
return 0;
}else{
return e.getCode() ;
}
}
}
调用的测试代码
package com.example;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.Locale;
//import com.example.MonthEnum;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
java.time.Month m=java.time.Month.of(9);
System.out.print( "month:");
System.out.println( m. getDisplayName(TextStyle.SHORT,Locale.ENGLISH));
m=Month.valueOf("OCTOBER");
System.out.print( "month:");
System.out.println( m.getValue());
System.out.println( m. getDisplayName(TextStyle.SHORT,Locale.ENGLISH));
MonthEnum e=MonthEnum.getEnumByCode(10);
System.out.print( "new month:");
System.out.print( e.getCode());
System.out.println( e.getName());
System.out.print( "new code:");
System.out.println( MonthEnum.valueByName("oct"));
}
}