一种从值转为枚举的方法

Open
#16 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
35/100
Issue type
Documentation
Clarity
Needs clarification
Activity status
Stale
Tech stack
java
Domain
documentation

Research direction

The issue provides a Java StatusEnum example for mapping an integer value to an enum, but it names no repository file, test, or documentation entry point. First identify where this explanation belongs and confirm the expected contribution; done should mean the example and its class-loading explanation are added in the agreed location.

Written by the indexing model from the issue text.

Description

代码示例:

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类加载,而类加载后枚举字段已被初始化完毕,所以这样是行得通的
Dominant language
Java
Stars
2k
Forks
717
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from seaswalker/jdk-sourcecode-analysis

All issues in seaswalker/jdk-sourcecode-analysis

Similar issues

More Java issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.