是否可以在 Java 枚举中实现某种形式的命名空间?
在下面的枚举中,我看到 Message
枚举中存在三个不同的消息类:Form
、Site
和 Admin.
是否可以在枚举中实现一种命名空间
机制,这样,
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;
}
}
In the enum below I see three three distinct classes of messages that exist within the Message
enum: Form
, Site
and Admin
.
Is it possible to implement a type of namespace
mechanism in an enum so that, instead of writing
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?
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以用包吗?
例如:
是您的基础包。然后你可以从那个
等等扩展......
You could use packages?
for example:
is your base package. Then you can expand from that
Et cetera...
您可以将
Message
设为声明枚举Site
和Admin
的接口。但是,当然,您不能传递Message
对象并期望一个枚举,而只是一个Message.
对象。你要这个做什么?
You could make
Message
an interface that declares enumsSite
andAdmin
. But then, of course, you can't pass around aMessage
object and expect an enum, just aMessage.<something>
object.What do you want this for?
当然,使用内部类就可以了。
我认为您可能会摆脱具有公共基类的重复代码,但我的记忆在扩展枚举方面很模糊,因此这可能不起作用......
Of course, just use inner classes.
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...