在Java中嵌套枚举 [英] Nesting enums in Java
问题描述
因此,如果类型A可以具有值1,2或3,并且类型B可以有价值4,5,6,我想能够做到这样的事情:
标志f =标志。 A.1;
f.getType() - 返回A
f.getValue() - 返回1
标志f2 = Flag.A 0.4; - 语法错误。
我正在疯狂地尝试在枚举中嵌套枚举 - 是我正在尝试的 - 我需要完整的枚举枚举,并用静态成员手工制作一个静态类吗?
我迄今所做的最大努力是:
public class Flag {
enum A extends Flag {
ONE(ONE),
TWO(TWO) ,
THREE(THREE);
private A(String value){
Flag.type =A;
Flag.value = value;
}
}
private static String type;
private static String value;
}
但是如果我这样做:
标志f = Flag.A.ONE;
类型不兼容。
你不能有一个数字作为枚举。它必须是一个标识符。
你可以这样做
interface Flag {
String getType();
int getValue();
枚举A implements Flag {
一,二,三;
String getType(){return getClass()。getSimpleName(); }
int getvalue(){return ordinal()+ 1; }
}
枚举B执行标志{
四,五,六;
String getType(){return getClass()。getSimpleName(); }
int getvalue(){return ordinal()+ 4; }
}
}
标志f = Flag.A.one;
然而,一个更简单的选项可能是
枚举标志{
A1,A2,A3,B4,B5,B6;
public String getType(){return name()。substring(0,1); }
public int getValue(){return name()。charAt(1) - '0'; }
}
标志f = Flag.A1;
I want to nest some enums. The object i'm representing are Flags, with a type, and a value. There are a discrete number of types, and each type has a distinct set of possible values.
So if Type A can have values 1, 2 or 3, and Type B can have values 4,5,6, I'd like to be able to do things like:
Flag f = Flag.A.1;
f.getType() - returns "A"
f.getValue() - returns "1"
Flag f2 = Flag.A.4; -- Syntax error.
I'm driving myself crazy trying to nest enums within enums - is what i'm trying possible - do I need to ditch enums altogether and handcraft a static class with static members?
My best effort so far is:
public class Flag {
enum A extends Flag {
ONE("ONE"),
TWO("TWO"),
THREE("THREE");
private A(String value) {
Flag.type = "A";
Flag.value = value;
}
}
private static String type;
private static String value;
}
But if I do:
Flag f = Flag.A.ONE;
The types are incompatible.
You cannot have a number as an enum. It has to be an identifier.
You can do this
interface Flag {
String getType();
int getValue();
enum A implements Flag{
one, two, three;
String getType() { return getClass().getSimpleName(); }
int getvalue() { return ordinal()+1; }
}
enum B implements Flag{
four, five, six;
String getType() { return getClass().getSimpleName(); }
int getvalue() { return ordinal()+4; }
}
}
Flag f = Flag.A.one;
However a simpler option may be
enum Flag {
A1, A2, A3, B4, B5, B6;
public String getType() { return name().substring(0,1); }
public int getValue() { return name().charAt(1) - '0'; }
}
Flag f = Flag.A1;
这篇关于在Java中嵌套枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!