枚举父接口
public interface BaseEnum {
Integer getCode ( ) ;
String getLabel ( ) ;
static < E extends Enum < E > & BaseEnum > E getEnumByCode ( Integer code, Class < E > clazz) {
Objects . requireNonNull ( code) ;
EnumSet < E > allEnums = EnumSet . allOf ( clazz) ;
return allEnums. stream ( )
. filter ( e -> e. getCode ( ) . equals ( code) )
. findFirst ( )
. orElse ( null ) ;
}
static < E extends Enum < E > & BaseEnum > E getEnumByLabel ( String label, Class < E > clazz) {
Objects . requireNonNull ( label) ;
EnumSet < E > allEnums = EnumSet . allOf ( clazz) ;
return allEnums. stream ( )
. filter ( e -> e. getLabel ( ) . equals ( label) )
. findFirst ( )
. orElse ( null ) ;
}
static < E extends Enum < E > & BaseEnum > String getLabelByCode ( Integer code, Class < E > clazz) {
E matchEnum = getEnumByCode ( code, clazz) ;
if ( matchEnum != null ) {
return matchEnum. getLabel ( ) ;
}
throw new RuntimeException ( "根据值获取文本标签失败" ) ;
}
static < E extends Enum < E > & BaseEnum , T > int getCodeByLabel ( String label, Class < E > clazz) {
E matchEnum = getEnumByLabel ( label, clazz) ;
if ( matchEnum != null ) {
return matchEnum. getCode ( ) ;
}
throw new RuntimeException ( "根据文本标签获取值失败" ) ;
}
}
枚举
public enum StateEnum implements BaseEnum {
ENABLE ( 1 , "启用" ) ,
DISABLE ( 0 , "禁用" ) ;
@Getter
private final Integer code;
@Getter
private final String label;
StateEnum ( Integer code, String label) {
this . code = code;
this . label = label;
}
}
测试代码
public static void main ( String [ ] args) {
final StateEnum s1 = BaseEnum . getEnumByCode ( 1 , StateEnum . class ) ;
System . out. println ( s1) ;
final StateEnum s2 = BaseEnum . getEnumByLabel ( "启用" , StateEnum . class ) ;
System . out. println ( s2) ;
final String label = BaseEnum . getLabelByCode ( 1 , StateEnum . class ) ;
System . out. println ( label) ;
final int code = BaseEnum . getCodeByLabel ( "禁用" , StateEnum . class ) ;
System . out. println ( code) ;
}
结果