[英]Is it possible to implement a form of namespacing in Java Enums?
In the enum below I see three three distinct classes of messages that exist within the Message
enum: Form
, Site
and Admin
. 在下面的枚举中,我看到Message
枚举中存在三种三种不同的消息类别: Form
, Site
和Admin
。
Is it possible to implement a type of namespace
mechanism in an enum so that, instead of writing 是否有可能在枚举中实现一种namespace
机制,以便代替编写
Message.SITE_ERROR
Message.ADMIN_ERROR
you write, this: 你这样写:
Message.Site.ERROR
Message.Admin.ERROR
so that Site
and Admin
represent the "namespace" below which additional categories of messages can exist? 以便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;
}
}
You could use packages? 您可以使用包裹吗?
for example: 例如:
com.foo.messages
is your base package. 是您的基本包装。 Then you can expand from that 然后,您可以从中扩展
com.foo.messages.site
com.foo.messages.admin
Et cetera... 等等...
You could make Message
an interface that declares enums Site
and Admin
. 您可以将Message
声明为枚举Site
和Admin
的接口。 But then, of course, you can't pass around a Message
object and expect an enum, just a Message.<something>
object. 但是,当然,您不能传递Message
对象并期望枚举,而只能是Message.<something>
对象。
What do you want this for? 你要干嘛
Of course, just use inner classes. 当然,只使用内部类。
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; }
}
}
I think you may get rid of the repeated code with a common base class but my memory is fuzzy on extending enums so that may not work... 我认为您可能会摆脱带有通用基类的重复代码,但是我对扩展枚举的记忆模糊,因此可能无法正常工作...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.