如何使用 Java 枚举模拟多层菜单系统?
我需要完成以下任务(这是一个简化版本):
enum Animals{
enum Cats{tabby("some value"), siamese("some value")},
enum Dogs{poodle("some value"), dachsund("some value")},
enum Birds{canary("some value"), parrot("some value")}
private String someValue = "";
private ShopByCategory(String someValue)
{
this.someValue = someValue;
}
public String getSomeValue()
{
return this.someValue;
}
}
以便我可以按如下方式访问这些项目:
string cat1 = Animals.Cats.tabby.getSomeValue;
string dog1 = Animals.Dogs.dachsund.getSomeValue;
string bird1 = Animals.Birds.canary.getSomeValue;
我尝试使用枚举执行此操作的原因是我需要能够访问每个层而无需a) 实例化一个类,b) 将层的名称隐藏在方法名称后面,或者 c) 使用迭代器遍历 EnumSet。
这有可能吗?除了枚举之外,您还有什么建议?
I need to accomplish the following (this is a simplified version):
enum Animals{
enum Cats{tabby("some value"), siamese("some value")},
enum Dogs{poodle("some value"), dachsund("some value")},
enum Birds{canary("some value"), parrot("some value")}
private String someValue = "";
private ShopByCategory(String someValue)
{
this.someValue = someValue;
}
public String getSomeValue()
{
return this.someValue;
}
}
So that I can access these items as follows:
string cat1 = Animals.Cats.tabby.getSomeValue;
string dog1 = Animals.Dogs.dachsund.getSomeValue;
string bird1 = Animals.Birds.canary.getSomeValue;
The reason why I am attempting to do this with enums is the fact that I need to be able to access each tier without having to a) instantiate a class, b) hide the names of the tiers behind a method name, or c) use an iterator to go through an EnumSet.
Is this at all possible? What would you suggest instead of enums?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是我最终实现解决方案的方式:
这样,我不必实例化该类或调用任何类特定的方法来获取我想要的信息。我可以得到所有“一些值”字符串,如下所示:
Here's how I finally ended up implementing my solution:
This way, I don't have to instantiate the class or call any class specific methods to get my desired info. I can get at all the "some value" strings like this: