如何从接受通用枚举的方法中返回通用枚举?

huangapple go评论80阅读模式
英文:

How to return a generic Enum from a method that accepts a generic Enum?

问题

我正在尝试编写一个实用方法,该方法将接受任何类型的枚举并返回相同类型的枚举,但具有不同的值。

假设我有以下两个枚举:

enum Pet {
    DOG("Puppy"),
    CAT("Jazmine"),
    LIZARD("Spock");

    private final String value;

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

    public String getValue() {
        return value;
    }
}

enum Topping {
    PEPPERONI("Meat Saucers"),
    ONION("Like Ogres"),
    ANCHOVIES("Spicy Fish");

    private final String value;

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

    public String getValue() {
        return value;
    }
}

在我的应用程序中,用户需要能够“编辑”枚举值。例如,当用户想要编辑他们的“Pet”时,他们会看到枚举值的列表,可以从该列表中选择一个新值。

我试图做的是编写一个方法,可以处理任意数量的不同类型的枚举(例如:既有“Pet”又有“Topping”)。

由于我对泛型不太熟悉,以下是一个非常简陋的示例,说明我试图做什么:

public static GenericEnumType changeValue(Enum<?> e) {
        
    // 向用户呈现e.values()列表,用户可以选择新值
    String newValue = getUserInput();
    return GenericEnumType.valueOf(newValue);
}

是否有办法实现这样的功能?
从我的研究中,我发现从通用枚举中检索值可能很困难,因为values()方法实际上在编译时不可用。

英文:

I am trying to write a utility method that will accept an enum of any type and return an enum of the same type, but with a different value.

Suppose I have the following two enum:

enum Pet {
    DOG(&quot;Puppy&quot;),
    CAT(&quot;Jazmine&quot;),
    LIZARD(&quot;Spock&quot;);

    private final String value;

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

    public String getValue() {
        return value;
    }
}

enum Topping {
    PEPPERONI(&quot;Meat Saucers&quot;),
    ONION(&quot;Like Ogres&quot;),
    ANCHOVIES(&quot;Spicy Fish&quot;);

    private final String value;

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

    public String getValue() {
        return value;
    }
}

In my application, a user needs the ability to "edit" an enum value. For example, when the user wants to edit their Pet, they are presented with a list of the enum values and can select a new one from that list.

What I'm trying to do is write one method that can handle any number of different types of enum (ie: both Pet and Topping).

Since I am not very familiar with generics yet, here is a very poorly "coded" example of what I'm trying to do:

public static GenericEnumType changeValue(Enum&lt;?&gt; e) {
        
    // Present user with list of e.values(), user can select new value
    String newValue = getUserInput();
    return GenericEnumType.valueOf(newValue);
}

Is there a way to accomplish such a thing?
From my research, I've found that it may be difficult to retrieve values from generic enum because the values() method is not actually available at compile time.

答案1

得分: 1

Enum.valueOf 可能会抛出 IllegalArgumentExceptionNullPointerException 异常。你应该处理它。

英文:
public static Enum&lt;?&gt; changeValue(Enum&lt;?&gt; e) {
    String newValue = getUserInput();
    return Enum.valueOf(e.getClass(), newValue);
}

Enum.valueOf could throws IllegalArgumentException and NullPointerException. You should handle it

答案2

得分: 0

你可以尝试这样做:

enum MyEnum1 { VALUE1, VALUE2 }
enum MyEnum2 { VALUE3, VALUE4 }

public static &lt;E extends Enum&lt;E&gt;&gt; E valueOf(
        Class&lt;E&gt; enumClass, String value) {
    return Enum.valueOf(enumClass, value);
}
然后

System.out.println(valueOf(MyEnum1.class, "VALUE1"));


当你需要一个接受任何类型的枚举的方法时,通常可以这样做。在这种特定情况下,由于你只是解析,可以简单地使用:

Enum.valueOf(MyEnum1.class, "VALUE1")

英文:

You can try this:

    enum MyEnum1 { VALUE1, VALUE2 }
    enum MyEnum2 { VALUE3, VALUE4 }

    public static &lt;E extends Enum&lt;E&gt;&gt; E valueOf(
            Class&lt;E&gt; enumClass, String value) {
        return Enum.valueOf(enumClass, value);
    }

Then

System.out.println(valueOf(MyEnum1.class, &quot;VALUE1&quot;));

This is generally what you can do when you need a method that accepts any types of enum. In this particular case, since you are parsing only, might as well simply use:

Enum.valueOf(MyEnum1.class, &quot;VALUE1&quot;)

答案3

得分: 0

我认为你正在尝试从给定的枚举中查找枚举值,如果是这样,你可以使用反射来查找它们。以下是我所做的事情。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Test {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
        System.out.println(changeValue(Pet.DOG));
    }
    
    public static Enum changeValue(Enum<?> e) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
        // 提供用户选择 e.values() 列表中的新值
        Method method = e.getClass().getDeclaredMethod("values");
        Object obj = method.invoke(null);
        System.out.println(Arrays.toString((Object[]) obj));
        
        String newValue = getUserInput();
        return e.valueOf(e.getClass(), newValue);
    }
    
    private static String getUserInput() throws IOException {
        System.out.println("从列表中选择一个枚举并输入名称:");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String name = reader.readLine();
        return name;
    }
}

enum Pet {
    DOG("Puppy"),
    CAT("Jazmine"),
    LIZARD("Spock");
    
    private final String value;
    
    Pet(String value) {
        this.value = value;
    }
    
    public String getValue() {
        return value;
    }
}

enum Topping {
    PEPPERONI("Meat Saucers"),
    ONION("Like Ogres"),
    ANCHOVIES("Spicy Fish");
    
    private final String value;
    
    Topping(String value) {
        this.value = value;
    }
    
    public String getValue() {
        return value;
    }
}

注意:这是你提供的代码的中文翻译,不包括代码本身。

英文:

I think you are facing with difficulty to find the enums from given enum. Then you can use reflection to find them. Following you can find what I did.

    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
System.out.println(changeValue(Pet.DOG));
}
public static Enum changeValue(Enum&lt;?&gt; e) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
// Present user with list of e.values(), user can select new value
Method method = e.getClass().getDeclaredMethod(&quot;values&quot;);
Object obj = method.invoke(null);
System.out.println(Arrays.toString((Object[]) obj));
String newValue = getUserInput();
return e.valueOf(e.getClass(),newValue);
}
private static String getUserInput() throws IOException {
System.out.println(&quot;select one of the enum from list and enter the name&quot;);
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
return name;
}
}
enum Pet {
DOG(&quot;Puppy&quot;),
CAT(&quot;Jazmine&quot;),
LIZARD(&quot;Spock&quot;);
private final String value;
Pet(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
enum Topping {
PEPPERONI(&quot;Meat Saucers&quot;),
ONION(&quot;Like Ogres&quot;),
ANCHOVIES(&quot;Spicy Fish&quot;);
private final String value;
Topping(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}

huangapple
  • 本文由 发表于 2020年8月6日 11:04:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63276232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定