枚举继承或类似的东西

发布于 2024-11-05 14:33:32 字数 409 浏览 0 评论 0原文

我有一个字符串(这是一条消息)作为输入,我需要根据该字符串执行 4 种可能的操作之一 我知道有 eum.valueOf() 选项,但我有 4 个不同的枚举,每个枚举都几乎没有可能的消息。

看起来像:

public enum first{ONE,TWO,THREE};
public enum second{FOUR,FIVE,SIX};
public enum third{SEVEN,EIGHT,NINE};

public void work(String message){
    //Here I want to compare message string to one of the 3 enums
}

是否可以在枚举的一种方法中执行此操作? 或者我应该尝试创建一个,如果出现异常,则尝试另一个,依此类推?

I have a string (which is a message) that I get as input and I need to do one of 4 possible things depending on the string
I know that there is eunm.valueOf() option, but I have 4 different enums, each with few possible messages.

looks something like:

public enum first{ONE,TWO,THREE};
public enum second{FOUR,FIVE,SIX};
public enum third{SEVEN,EIGHT,NINE};

public void work(String message){
    //Here I want to compare message string to one of the 3 enums
}

is it possible to do this in one method of the enum?
or should I just try to create one, and if I get an exception try the other and so on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

和影子一齐双人舞 2024-11-12 14:33:32

正如其他人评论的那样,最好考虑一下您是否真的需要 4 个不同的枚举。

但如果你这样做,你可以让他们实现一个通用接口。然后,您可以将输入字符串映射到适当的枚举成员,并调用其方法来完成您想要的操作。 This假设

public interface SomeInterface {
  void doSomething();
};

public enum First implements SomeInterface {
  ONE,TWO,THREE;
  @Override
  public void doSomething() { ... }
};
...
Map<String, SomeInterface> myMap = new HashMap<String, SomeInterface>();
for (First item : First.values()) {
  myMap.put(item.toString(), item);
}
...

public void work(String message){
  SomeInterface obj = myMap.get(message);
  if (obj != null) {
    obj.doSomething();
  }
}

您想做的 4 件可能的事情对应于 4 个枚举。如果没有,您也可以为每个枚举成员单独重写该方法,例如

public enum First implements SomeInterface {
  ONE,
  TWO {
    @Override
    public void doSomething() { // do something specific to TWO }
  },
  THREE;
  @Override
  public void doSomething() { // general solution for all values of First }
};

As others have commented, it may be better to think through whether you really need 4 distinct enums.

But if you do, you could have them implement a common interface. Then you can map the input strings to the appropriate enum member, and call its method to accomplish what you want. Something like

public interface SomeInterface {
  void doSomething();
};

public enum First implements SomeInterface {
  ONE,TWO,THREE;
  @Override
  public void doSomething() { ... }
};
...
Map<String, SomeInterface> myMap = new HashMap<String, SomeInterface>();
for (First item : First.values()) {
  myMap.put(item.toString(), item);
}
...

public void work(String message){
  SomeInterface obj = myMap.get(message);
  if (obj != null) {
    obj.doSomething();
  }
}

This assumes that the 4 possible things you want to do correspond to the 4 enums. If not, you can override the method separately for each and any enum member too, e.g.

public enum First implements SomeInterface {
  ONE,
  TWO {
    @Override
    public void doSomething() { // do something specific to TWO }
  },
  THREE;
  @Override
  public void doSomething() { // general solution for all values of First }
};
傲影 2024-11-12 14:33:32

Java 中的枚举是成熟的类。个人价值观甚至可以凌驾于满足其需求的行为之上。非常酷。您可以利用这一点来发挥您的优势:

public enum Value implements Worker
{
    ONE,
    TWO,
    THREE
    {
        @Override
        public void doWork(String message)
        {
            // overrides behavior of base enum
        }
    },
    FOUR,
    /* ... */,
    NINE;

    private final String message;

    Value() { this(""); }
    Value(String message) { this.message = message; }

    public void doWork(String message)
    {
        if (this.message.equals(message))
        {
            /* ... */
        }
    }
}

public interface Worker
{
    void doWork(String message);
}

Enumerations in Java are full blown classes. Individual values can even override the behavior to meet their needs. It's pretty cool. You can use this to your advantage:

public enum Value implements Worker
{
    ONE,
    TWO,
    THREE
    {
        @Override
        public void doWork(String message)
        {
            // overrides behavior of base enum
        }
    },
    FOUR,
    /* ... */,
    NINE;

    private final String message;

    Value() { this(""); }
    Value(String message) { this.message = message; }

    public void doWork(String message)
    {
        if (this.message.equals(message))
        {
            /* ... */
        }
    }
}

public interface Worker
{
    void doWork(String message);
}
薄荷港 2024-11-12 14:33:32

您可以创建所有这些的地图

 static final Map<String, Enum> enumMap = new LinkedHashMap<String, Enum>(){{
     for(First e: First.values()) put(e.name(), e);
     for(Second e: Second.values()) put(e.name(), e);
     for(Third e: Third.values()) put(e.name(), e);
 }};

 Enum e = enumMap.get(name);

You can create a Map of them all

 static final Map<String, Enum> enumMap = new LinkedHashMap<String, Enum>(){{
     for(First e: First.values()) put(e.name(), e);
     for(Second e: Second.values()) put(e.name(), e);
     for(Third e: Third.values()) put(e.name(), e);
 }};

 Enum e = enumMap.get(name);
廻憶裏菂餘溫 2024-11-12 14:33:32

您真正要寻找的是其他枚举的聚合。最简单的方法是创建一个新的枚举,将所有这些选择放入一个新的枚举中。效果如下:

public enum Combination {
    NEWONE(first.ONE), NEWTWO(first.TWO), NEWTHREE(first.THREE),
    NEWFOUR(second.FOUR), NEWFIVE(second.FIVE), NEWSIX(second.SIX),
    NEWSEVEN(third.SEVEN), NEWEIGHT(third.EIGHT), NEWNINE(third.NINE);

    private String contents;

    public Combination(first f) {
        contents = f.toString();
    }

    public Combination(second s) {
        contents = s.toString();
    }

    public Combination(third t) {
        contents = t.toString();
    }

    public String toString() {
        return contents;
    }
}

这将更正确地将先前的枚举聚合到单个数据结构中。

What you're really looking for is a aggregation of the other enums. The easiest way to get that is to make a new enum that puts all of those choices in a new enum. Something to this effect:

public enum Combination {
    NEWONE(first.ONE), NEWTWO(first.TWO), NEWTHREE(first.THREE),
    NEWFOUR(second.FOUR), NEWFIVE(second.FIVE), NEWSIX(second.SIX),
    NEWSEVEN(third.SEVEN), NEWEIGHT(third.EIGHT), NEWNINE(third.NINE);

    private String contents;

    public Combination(first f) {
        contents = f.toString();
    }

    public Combination(second s) {
        contents = s.toString();
    }

    public Combination(third t) {
        contents = t.toString();
    }

    public String toString() {
        return contents;
    }
}

This will more correctly aggregate the previous enums into a single data structure.

暖树树初阳… 2024-11-12 14:33:32

即使在评论中给出了奇数/偶数示例,我也不认为多个枚举是这里的方法。我会使用类似的东西(警告,未经测试):

public enum Numbers {
ONE("first"), TWO("first"), THREE("first"), FOUR("second"), FIVE("second"), SIX("second"), SEVEN("third"), EIGHT("third"), NINE("third")

private String type;

Numbers(String t) { this.type = t; }
String getType { return this.type; }
}

然后您可以使用 valueOf() 查找枚举元素,并使用 getType() 找出您的三个元素中的哪一个它所属的类别。

Even given your odd/even example in the comments, I don't feel multiple enums are the way to go here. I would use something like (warning, untested):

public enum Numbers {
ONE("first"), TWO("first"), THREE("first"), FOUR("second"), FIVE("second"), SIX("second"), SEVEN("third"), EIGHT("third"), NINE("third")

private String type;

Numbers(String t) { this.type = t; }
String getType { return this.type; }
}

Then you can use valueOf() to look up the enum element, and getType() to find out which of your three categories it belongs to.

北斗星光 2024-11-12 14:33:32

目前尚不完全清楚您要问什么,但也许您想定义字符串和常量之间的映射,如下所示:

enum Type { FIRST, SECOND, THIRD };
Map<String, Type> mapping = new HashSet<String, Type>(){{
    put("ONE", Type.FIRST);
    put("TWO", Type.FIRST);
    //...
    put("NINE", Type.THIRD);
}};

public Type getTypeFromString(String s) {
    return mapping.get(s);
}

It isn't entirely clear what you are asking, but perhaps you want to define a mapping between strings and constants, like this:

enum Type { FIRST, SECOND, THIRD };
Map<String, Type> mapping = new HashSet<String, Type>(){{
    put("ONE", Type.FIRST);
    put("TWO", Type.FIRST);
    //...
    put("NINE", Type.THIRD);
}};

public Type getTypeFromString(String s) {
    return mapping.get(s);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文