我需要完成以下操作(这是一个简化版本):
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。
这一切都可能吗?你会建议什么而不是枚举?
答案 0 :(得分:1)
//Animals.java
public class Animals {
public static class Cats {
public static final String tabby = "some value";
public static final String siamese = "some value";
}
public static class Dogs {
public static final String poodle = "some value";
public static final String dachsund = "some value";
}
public static class Birds {
public static final String canary = "some value";
public static final String parrot = "some value";
}
}
//ShopByCategory.java
public class ShopByCategory {
private String someValue;
public ShopByCategory(String value){
this.someValue = value;
}
public String getSomeValue(){
return this.someValue;
}
}
//Main.java - an example of what you can do
public class Main {
public static void main(String[] args){
ShopByCategory sbc = new ShopByCategory(Animals.Birds.canary);
System.out.println(sbc.getSomeValue());
System.out.println(Animals.Dogs.poodle);
}
}
答案 1 :(得分:1)
以下是我最终实现我的解决方案的方式:
public static class Animals()
{
public enum Cats()
{
tabby("some value"),
siamese("some value");
private String someValue = "";
private ShopByCategory(String someValue)
{
this.someValue = someValue;
}
public String getSomeValue()
{
return this.someValue;
}
}
public enum Dogs()
{
poodle("some value"),
dachsund("some value");
private String someValue = "";
private ShopByCategory(String someValue)
{
this.someValue = someValue;
}
public String getSomeValue()
{
return this.someValue;
}
}
public 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;