Skip to content
framiere edited this page Nov 24, 2011 · 4 revisions

@EnumId

- WORK IN PROGRESS - (Initial copy of old documentation)

Overview

There are situations where enum.valueOf() just isn't enough, where you need other fields to be indentifier for all the different enum values. Doing that usually involved a fair amount of boilerplate. Now it's just one simple annotation.

Usage

With Lombok

import lombok.EnumId;
import lombok.RequiredArgsConstructor;
import lombok.Getter;

public class EnumIdExample {
  @RequiredArgsConstructor
  public enum Status {
    WAITING(0),
    READY(1),
    SKIPPED(-1),
    COMPLETED(5);
   
    @EnumId
    @Getter
    private final int code;
  }
}

Vanilla Java

class EnumIdExample {
  public enum Status {
    WAITING(0),
    READY(1),
    SKIPPED(-1),
    COMPLETED(5);
    
    private static final java.util.Map<java.lang.Integer, Status> $CODE_LOOKUP = new java.util.HashMap<java.lang.Integer, Status>();
    static {
      for (Status status : Status.values()) {
        $CODE_LOOKUP.put(status.code, status);
      }
    }
    
    private final int code;
    
    private Status(final int code) {
      this.code = code;
    }
    
    public int getCode() {
      return this.code;
    }
    
    public static Status findByCode(final int code) {
      if ($CODE_LOOKUP.containsKey(code)) {
        return $CODE_LOOKUP.get(code);
      }
      throw new java.lang.IllegalArgumentException(java.lang.String.format("Enumeration 'Status' has no value '%s'", code));
    }
  }
}
Clone this wiki locally