Skip to content

Instantly share code, notes, and snippets.

@gakuzzzz

gakuzzzz/0.md

Last active Apr 2, 2019
Embed
What would you like to do?
EnumReverseLookup

共通コード

public class EnumReverseLookup<E extends Enum<E>, ATTR> {

    private final Class<E> enumClass;
    private final Function<E, ATTR> getter;

    public EnumReverseLookup(final Class<E> enumClass, final Function<E, ATTR> getter) {
        this.enumClass = enumClass;
        this.getter = getter;
    }

    public E lookup(ATTR attribute) {
        return Arrays
            .stream(enumClass.getEnumConstants())
            .filter(e -> getter.apply(e).equals(attribute))
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException());
    }
}

Enum側

public enum RegistrationStatus {
    TEMPORARY("0", "仮会員"), REGULAR("1", "正会員");

    private String code;
    private String text;

    private RegistrationStatus(String code, String text) {
        this.code = code;
        this.text = text;
    }

    public String getCode() {
        return code;
    }

    public String getText() {
        return text;
    }

    public static final EnumReverseLookup<RegistrationStatus, String> byCode =
        new EnumReverseLookup<>(RegistrationStatus.class, RegistrationStatus::getCode);
}

利用側

public class Hoge {
    void hoge() {
        RegistrationStatus.byCode.lookup("0");
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment