如何将Java枚举值用作真正的静态常量

时间:2013-11-12 19:53:52

标签: java oop static enums

好的,所以我做了一些关于常数以及它们应该如何设计和使用的研究。对于我的应用程序,有许多枚举可以组合彼此相关的术语。

我的想法是,当我使用数百个参数(其中许多使用多次)和方法开发Web服务时,我可以使用枚举的值进行注释。在此之前,有一个巨大的,令人作呕的Constants文件,其中包含冗余和未维护的值。

所以,这是我想要使用的枚举:

package com.company.ws.data.enums;

/** This {@link Enum} contains all web service methods that will be used. **/
public enum Methods {

    /** The name of the web service for looking up an account by account number. **/
    FIND_ACCOUNT_BY_ACCOUNT_NUMBER("accountByNumberRequest");

    /** The String value of the web service method name to be used in SOAP **/
    private String value;

    private Methods(String value) {
        this.value = value;
    }

    /**
     * @return the String value of the web service method name to be used in
     *         SOAP
     */
    public String getValue() {
        return this.value;
    }
}

这是我想要使用它的地方:

package com.company.ws.data.models;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import com.company.ws.data.enums.Methods;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = **Methods.FIND_ACCOUNT_BY_ACCOUNT_NUMBER**, namespace = "com.company.ws")
public class AccountByNumberRequest{
}

所以,如果我尝试以上操作,我会得到错误Type mismatch: cannot convert from Methods to String,这非常有意义。所以,让我们尝试访问枚举的实际值:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = **Methods.FIND_ACCOUNT_BY_ACCOUNT_NUMBER.getValue()**, namespace = "")
public class AccountByNumberRequest extends RequestByAccount {
}

这样做,我收到此错误消息:The value for annotation attribute XmlRootElement.name must be a constant expression

那么,我可以使用像我想要的枚举吗?它们可以用来代替最终类中定义的真实静态常量值吗?或者我是否处于一个奇怪的编译时状态,其中在枚举本身被加载并使用其值实例化之前评估注释?指导资源:http://www.javapractices.com/topic/TopicAction.do?Id=1

2 个答案:

答案 0 :(得分:3)

不,你不能。根据JLS,Methods.getValue()的值不是常量表达式,这是编译器告诉你的。

答案 1 :(得分:1)

注释不会被评估或实例化。它们只是告诉编译器将其他数据(而不是代码)嵌入到编译类中的指令,稍后您可以使用反射API进行查询。

因此,可以设置为注释值的唯一事物是常量 - 换句话说,在编译时已知的值可以减少到可以放在类的常量池中的值:原始值,字符串,对其他类的引用,对枚举值的引用,上述数组。

因此,您无法从方法调用中设置注释值 - 只有在运行时执行时才能知道它们的值。 (好吧,也许不是如果方法总是返回相同的值,但为了简化语言和编译器,Java规范不要求编译器足够复杂以便弄明白。)