【问题标题】:Trouble to use generic with Enum in Java abstract class在 Java 抽象类中将泛型与枚举一起使用时遇到问题
【发布时间】:2023-02-21 22:53:25
【问题描述】:

我有公共抽象类 AbstractDevice 来扩展某些由 String 命令控制的某些设备类(如阀门、电机、温度传感器等),处理如下:

public class Valve extends AbstractDevice {

  protected static enum Mode {OPEN, CLOSE};

  protected Mode mode;

  ...

  protected void processCommand(String command) {

     mode = Enum.valueOf(Mode.class, command);

    switch (mode)

      case OPEN: ...(execute OPEN command)

}

它工作正常。

但是当我尝试在抽象类中移动字符串到枚举的转换以使用任何命令集时:

public abstract class AbstractDevice {

static protected <E> E getElement(Class<E> enumType, String elementName) {

  try {

    return Enum.valueOf(enumType, elementName);

  } catch (IllegalArgumentException e) {

    return null;

  }

}

我有编译错误The method valueOf(Class&lt;T&gt;, String) in the type Enum is not applicable for the arguments (Class&lt;E&gt;, String)

这里出了什么问题?

【问题讨论】:

  • 那是爪哇吗?您应该将语言添加到标签中,否则人们将看不到您的问题。此外,提供格式正确的代码会增加人们阅读它的意愿......
  • 谢谢,添加了标签,格式化了代码——这是我的第一个问题。

标签: java string generics enums


【解决方案1】:

Enum.valueOf(Class, String) - 返回指定的枚举常量枚举类具有指定的名称。

所以将 getElement 方法签名更改为以下内容

static protected <E extends Enum<E>> E getElement(Class<E> enumType, String elementName) {
    try {
        return Enum.valueOf(enumType, elementName);
    } catch (IllegalArgumentException e) {
        return null;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2011-07-29
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多