2012-04-05 65 views
2

我想在Enum中声明静态(或非静态)变量。我需要这个,因为我想将枚举值与某些字符串关联。但我不想硬编码这些字符串。我想用String常量来使用我的应用程序范围的类。 也就是说我想写像这里面enum declaraton,但编译时错误:如何在Java中的Enum中声明字段?

public enum MyEnum { 
     private static final AppConstants CONSTANTS = AppConstants.getInstance(); 

     ONE(CONSTANTS.one()), 
     TWO(CONSTANTS.two()); 
} 

我怎么能枚举把一个领域?

+0

为什么你的AppConstants有一个get实例?它可以不是一个'enum'以及一个实例吗? – 2012-04-05 12:13:55

+1

事实上,我使用GWT,并有'私人AppMessages MESSAGES =(AppMessages)GWT.create(AppMessages.class);' – MyTitle 2012-04-05 12:20:33

回答

5

这是限制之一的第一要素,枚举值必须指定第一但你总是可以指同一singelton在每一个实例...

enum MyEnum { 

    ONE(Test.getInstance().one()), 
    TWO(Test.getInstance().two()); 

    public final String val; 

    MyEnum(String val) { this.val = val; } 
} 

实施例,其输出 “你好”:

public class Test { 
    public static void main(String[] args) { 
     System.out.println(MyEnum.ONE.val); 
    } 

    public String one() { 
     return "hello"; 
    } 
    public String two() { 
     return "world" ; 
    } 

    static Test instance; 
    public synchronized static Test getInstance() { 
     if (instance == null) 
      instance = new Test(); 
     return instance; 
    } 
} 
2

枚举常量必须在枚举

public enum MyEnum { 

    ONE,TWO; 
    private static final AppConstants CONSTANTS = AppConstants.getInstance(); 

    @Override 
public String toString() { 
     if(this==ONE){ 
      return CONSTANTS.one(); 
     } else if(this==TWO){ 
      return CONSTANTS.two(); 
     } 
    return null; 
} 
} 
+0

-1,否则你不能这样做,因为:'不能在定义之前引用一个字段! – dacwe 2012-04-05 12:10:38

+0

-1这是行不通的! – adarshr 2012-04-05 12:10:52

+0

谢谢,但现在提交CONSTANTS是不可见的枚举常量:) – MyTitle 2012-04-05 12:11:17

2

这有点哈克。但你必须稍微改变你的AppConstants类。

public enum MyEnum { 
    ONE(getConstant("one")), 
    TWO(getConstant("one")); 

    private static final AppConstants CONSTANTS = AppConstants.getInstance(); 

    private static String getConstant(String key) { 
     // You can use a map inside the AppConstants or you can 
     // invoke the right method using reflection. Up to you. 
     return CONSTANTS.get(key); 
    } 

    private MyEnum(String value) { 

    } 
}