Skip to content
peichhorn edited this page Jun 30, 2012 · 4 revisions

@EnumId

Overview

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

Example

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 for 'code = %s'", code));
    }
  }
}

Behind the Scenes

This annotation instructs lombok to create a lookup hash-map and a findByFIELD_NAME() method.

Configuration

Nothing to configure yet.