[英]Java: How can enum constant can have a constructor and methods associated with it if it is static in nature
[英]How can a Java enum value be used as a true Static Constant
好的,所以我做了一些关于常数的研究以及它们应该如何设计和使用。 对于我的应用程序,有许多枚举可以组合彼此相关的术语。
我的想法是,当我使用数百个参数(其中许多使用不止一次)和方法开发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
完全有意义的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
你不能。 根据JLS, Methods.getValue()
值不是常量表达式,这是编译器告诉您的。
注释不会被评估或实例化。 它们只是告诉编译器将其他数据(而不是代码)嵌入到编译类中的指令,稍后您可以使用反射API进行查询。
因此,可以设置为注释值的唯一事物是常量 - 换句话说,在编译时已知的值可以减少到可以放在类的常量池中的值:原始值,字符串,对其他类的引用,对枚举值的引用,以上的数组。
因此,您无法从方法调用中设置注释值 - 只有在运行时执行时才能知道它们的值。 (好吧,如果方法总是返回相同的值,也许不是,但为了简化语言和编译器,Java规范不需要编译器足够复杂来解决这个问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.