java 枚举共享静态查找方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10121988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:42:25  来源:igfitidea点击:

Enums shared static look-up method

javaenums

提问by Boosty

I have the following Enum:

我有以下枚举:

public enum MyEnum{
    A(10, "First"), //
    B(20, "Second"), //
    C(35, "Other options");

    private Integer code;
    private String description;

    private MyEnum(Integer code, String description) {
        this.code = code;
        this.description = description;
    }

    public Integer getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    public static MyEnum getValueOf(Integer code) {
        for (MyEnum e : MyEnum.values()) {
            if (e.getCode().equals(code)) {
                return e;
            }
        }
        throw new IllegalArgumentException("No enum const " + MyEnum.class.getName() + " for code \'" + code
                + "\'");
    }
}

Which works fine. The getValueOf-method exists because when communicating with an external partner, we only get the code (they chose) to map to. I need the description because I need to show a meaningfull phrase in the GUI.

哪个工作正常。本getValueOf-方法的存在是因为与外部合作伙伴沟通时,我们只获取代码(他们选择)映射到。我需要描述,因为我需要在 GUI 中显示一个有意义的短语。

But I now have a number of similar enum classes. All having their own code & description, and they need the same lookup functionality. I wanted the getValueOf-method to be generic so I don't need to support 30+ different enums for basically the same method.

但是我现在有许多类似的枚举类。都有自己的代码和描述,他们需要相同的查找功能。我希望getValueOf-method 是通用的,所以我不需要为基本相同的方法支持 30 多个不同的枚举。

To solve this I wanted to make an abstract class to define this method and implement some of the common logic but this is impossible because I can't extend Enum.

为了解决这个问题,我想创建一个抽象类来定义此方法并实现一些通用逻辑,但这是不可能的,因为我无法扩展Enum.

Then I tried to make a Utility class with the following method:

然后我尝试使用以下方法创建一个实用程序类:

public static <T extends Enum<T>> T getValueOf(Enum<T> type, Integer code) {...}

But generics with Enums are confusing and I don't understand how to get this working.

但是枚举的泛型令人困惑,我不明白如何让它工作。

Basically what I want to know is: What is a good approach to define a common utility to an enum?

基本上我想知道的是:定义枚举的通用实用程序的好方法是什么?

采纳答案by Péter T?r?k

You need to pass the actual enum class object as a parameter to your method. Then you can get the enum values using Class.getEnumConstants().

您需要将实际的枚举类对象作为参数传递给您的方法。然后您可以使用Class.getEnumConstants().

In order to be able to access getCode()on the instances, you should define it in an interface and make all your enum types implement that interface:

为了能够访问getCode()实例,您应该在一个接口中定义它并使您的所有枚举类型实现该接口:

interface Encodable {
    Integer getCode();
}

public static <T extends Enum<T> & Encodable> T getValueOf(Class<T> enumClass, Integer code) {
    for (T e : enumClass.getEnumConstants()) {
        if (e.getCode().equals(code)) {
            return e;
        }
    }
    throw new IllegalArgumentException("No enum const " + enumClass.getName() + " for code \'" + code
            + "\'");
}

...

public enum MyEnum implements Encodable {
    ...
}

MyEnum e = getValueOf(MyEnum.class, 10);

回答by Michael Schmei?er

This is a bit tricky because the values()method is static. You would actually need reflection, but there is a nice way to hide this using standard library functionality.

这有点棘手,因为该values()方法是静态的。您实际上需要反射,但有一种很好的方法可以使用标准库功能来隐藏它。

First, define an interface with the methods common to all of your enum types:

首先,使用所有枚举类型通用的方法定义一个接口:

public interface Common {
    Integer getCode();
    String getDescription();
}

Then, make all your enums implement this interface:

然后,让你的所有枚举实现这个接口:

public enum MyEnum implements Common {...}

The static method you want to have then looks like:

您想要的静态方法如下所示:

public static <T extends Enum<T> & Common> T getValueOf( Class<T> type, Integer code ) {
    final EnumSet<T> values = EnumSet.allOf( type );
    for(T e : values) {
        if(e.getCode().equals( code )) {
            return e;
        }
    }
    throw new IllegalArgumentException( "No enum const " + type.getName() + " for code \'" + code + "\'" );
}