简体   繁体   English

通用枚举迭代器Java

[英]Generic enum iterator java

My Enum 我的枚举

public enum ExamStausEnum {

    RESULTAWAITED("Result Awaiting"), 
    PASSED("Passed"), 
    FAILED("Failed");

    private String value;

    ExamStausEnum(String value) {
        this.value = value;
    }

    @JsonValue
    public String getValue() {
        return value;
    }
}

Generic Iterator Enum 通用迭代器枚举

static <E extends Enum <E>> void foo(Class<E> elemType) {
    for (E e : java.util.EnumSet.allOf(elemType)) {
        System.out.println(e);
    }
}

Result : 结果:

RESULTAWAITED
PASSED
FAILED

How can I print the constructor values ? 如何打印构造函数值?

Result Awaiting
Passed
Failed

It's unavoidable to add another parameter to have an abstraction of the getValue() call: 不可避免地要添加另一个参数来抽象getValue()调用:

static <E extends Enum <E>> void foo(Class<E> elemType, Function<? super E, ?> f) {
    for(E e : java.util.EnumSet.allOf(elemType)) {
        System.out.println(f.apply(e));
    }
}

Then, you may it invoke for arbitrary enum types not necessarily having that method, eg 然后,您可以调用不一定具有该方法的任意enum类型,例如

foo(Thread.State.class, Object::toString);

or for your specific enum having the method: 或对于具有以下方法的特定enum

foo(ExamStausEnum.class, ExamStausEnum::getValue);

Even more use cases are possible: 可能还有更多用例:

foo(Thread.State.class, Enum::name);

or 要么

foo(ExamStausEnum.class, Enum::ordinal);

Of course, you may also let your ExamStausEnum type override the toString() method, eliminating the need for foo to call the getValue() method. 当然,您还可以让您的ExamStausEnum类型覆盖toString()方法,从而无需foo来调用getValue()方法。

the more foreward way is to create an interface declaring the getValue() method implemented by all your enums. 更先进的方法是创建一个接口,声明所有枚举实现的getValue()方法。

interface EnumWithValue{
   @JsonValue
   String getValue();
}

public enum ExamStausEnum implements EnumWithValue {

    RESULTAWAITED("Result Awaiting"), 
    PASSED("Passed"), 
    FAILED("Failed");

    private String value;

    ExamStausEnum(String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return value;
    }
}

then you can cast your enum in foo : 然后可以将您的枚举转换为foo

static <E extends Enum <E>> void foo(Class<E> elemType) {
    for (E e : java.util.EnumSet.allOf(elemType)) {
        System.out.println(((EnumWithValue)e).getValue());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM