0
点赞
收藏
分享

微信扫一扫

常量类定义的两种方式

三分梦_0bc3 2022-05-03 阅读 57
java

一、第一种常量类定义

定义

public class ConstClass {
    public static String AHS= "xxx";

    /**
     * 审核状态
     */
    public interface AuditState{
        // 待审核
        String AUDIT_ZERO = "0";
        // 审核通过
        String AUDIT_ONE= "1";
        // 审核失败
        String AUDIT_TWO= "2";
    }
}

使用

public static void main(String[] args) {
      String ahs= ConstClass.AHS;
	  String state= ConstClass.AuditState.AUDIT_ZERO;  
}

二、第二种常量类定义

定义

public interface NameCodePrincipal {
    String getName();
    int getCode();
}
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Getter;

@Getter
public enum AuditState implements NameCodePrincipal {
    AUDIT_ZERO("待审核", 0);
    AUDIT_ONE("审核通过", 1);
    AUDIT_TWO("审核失败", 2);

    private final String name;
    @JsonValue
    private final int code;

    AuditState(String name, int code) {
        this.name = name;
        this.code = code;
    }

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public static AuditState codeOf(int code) {
        for (AuditState auditState : AuditState.values()) {
            if (auditState.getCode() == code) {
                return auditState;
            }
        }
        return null;
    }
}

使用

public interface NameCodePrincipal {
    int code = AuditState.AUDIT_ZERO.getCode();
}
举报

相关推荐

0 条评论