Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一种从值转为枚举的方法 #16

Open
seaswalker opened this issue Nov 27, 2020 · 0 comments
Open

一种从值转为枚举的方法 #16

seaswalker opened this issue Nov 27, 2020 · 0 comments

Comments

@seaswalker
Copy link
Owner

seaswalker commented Nov 27, 2020

代码示例:

public enum StatusEnum {

    CREATING(0),
    PUBLISHED(1),
    FINISHED(2);

    private final int status;

    StatusEnum(int status) {
        this.status = status;
    }

    public int getStatus() {
        return status;
    }

    private static final Map<Integer, StatusEnum> mapper = new HashMap<>(3);

    static {
        Arrays.stream(StatusEnum.values()).forEach(
            statusEnum -> mapper.put(statusEnum.getStatus(), statusEnum)
        );
    }
    
    /**
     * 将status值转为枚举.
     */
    public static StatusEnum fromStatus(final Integer status) {
        if (status == null) {
            return null;
        }

        return mapper.get(status);
    }

}

枚举的实现原理是:

  1. 枚举值实际上是public static final的字段
  2. 枚举不允许在枚举值之前存在任何代码
  3. fromStatus的调用导致StatusEnum类加载,而类加载后枚举字段已被初始化完毕,所以这样是行得通的
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant