[英]Is it possible to implement a form of namespacing in Java Enums?
在下面的枚举中,我看到Message
枚举中存在三种三种不同的消息类别: Form
, Site
和Admin
。
是否有可能在枚举中实现一种namespace
机制,以便代替编写
Message.SITE_ERROR
Message.ADMIN_ERROR
你这样写:
Message.Site.ERROR
Message.Admin.ERROR
以便Site
和Admin
代表“名称空间”,在其下方可以存在其他类别的消息?
public enum Message {
//FORM
FORM_EMPTY("You've gotta put something in the form."),
//SITE
SITE_ERROR("Whoa. What happened?"),
SITE_ALERT("Hey, it's that time again.");
//ADMIN
ADMIN_ERROR("Gotta look into this, dude."),
ADMIN_ALERT("Time to get the lead out.");
private String messageString;
private Message(String messageString){
this.messageString=messageString;
}
@Override
public String toString() {
return messageString;
}
}
您可以使用包裹吗?
例如:
com.foo.messages
是您的基本包装。 然后,您可以从中扩展
com.foo.messages.site
com.foo.messages.admin
等等...
您可以将Message
声明为枚举Site
和Admin
的接口。 但是,当然,您不能传递Message
对象并期望枚举,而只能是Message.<something>
对象。
你要干嘛
当然,只使用内部类。
public interface State {
String getMessageString();
}
public class Message {
public static enum Form implements State {
EMPTY("You've gotta put something in the form."),
private final String msg;
public Form(String msg) { this.msg = msg; }
public String getMessageString() { return msg; }
}
public static enum Site implements State {
ERROR("Whoa. What happened?"),
ALERT("Hey, it's that time again.");
private final String msg;
public Site(String msg) { this.msg = msg; }
public String getMessageString() { return msg; }
}
public static enum Admin implements State {
ADMIN_ERROR("Gotta look into this, dude."),
ADMIN_ALERT("Time to get the lead out.");
private final String msg;
public Admin(String msg) { this.msg = msg; }
public String getMessageString() { return msg; }
}
}
我认为您可能会摆脱带有通用基类的重复代码,但是我对扩展枚举的记忆模糊,因此可能无法正常工作...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.