接口可以要求类定义内部枚举吗?
我想定义一个接口,以便所有实现它的类都将定义一个名为 Fields
的内部枚举。这在Java中可能吗?
编辑:我正在使用 Java (Servlet/JSP) 创建动态 Web 应用程序。我试图让我的模型都具有 save() 方法,以便将它们存储在数据库中。为了表示系统中用户的数据和字段,我想使用 Map
。但我想将 save()
方法放入接口中,因此我想确保所有可保存对象都有一个 Fields
枚举。例如,User
类可以定义如下内容:
public class User {
enum Fields { USERNAME, PASSWORD }
}
I want to define an interface, so that all the classes implementing it will define an internal enum named Fields
. Is that possible in Java?
EDIT: I am creating a dynamic web application using Java (Servlets/JSP). I am trying to get my models to all have save()
methods, so that they will be stored in the database. To represent the data and the fields of, say, a user in the system, I want to use Map<User.Fields, Object>
. But I want to put the save()
method in an interface, so I want to make sure that all the saveable objects have a Fields
enum. For example, the User
class can define something like:
public class User {
enum Fields { USERNAME, PASSWORD }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我用来解决这个问题的一种技术是定义一个枚举类型的接口,这样你就可以将一个特定的枚举与一个类“连接”起来,然后用子类定义该枚举,如下所示:
奇怪的是,你必须<代码>导入静态mypackage.MySubClass.MyEnum;
One technique I've used to address this issue is is to define an enum-typed interface, so you can "join" a particular enum with a class, then define that enum with the subclass, like this:
Oddly, you have to
import static mypackage.MySubClass.MyEnum;
不,但你可以这样做:
no, but you can do something like:
不,你不能。
为什么不在父接口中使用枚举。
编辑回答问题的编辑:
你不应该这样做。相反,有一个像这样的界面:
只需寻找备忘录模式,它可能会对您有所帮助。
No you can't .
Why not have the enum in the parent interface.
EDIT to answer the EDIT of question:
You shouldn't do like this. Instead have a interface like this:
Just look for the memento pattern, it may help you.
正如苏拉吉所说,不,不可能。然而你这样做的目的是什么?如果每个子类定义了自己的字段集,您可以强制使用 getFields 方法,返回一组实现另一个接口(和/或 Enum)的对象。或者只是根据名称,您是否需要反射 API(即 getClass().getDeclaredFields() )?
As Suraj said, nope, not possible. What is your intention by this however? If each subclass defines its own set of fields, You could force a getFields method, returning a Set of objects implementing another interface (and / or Enum). Or just going by names, are you needing the reflexions API (i.e. getClass().getDeclaredFields() )?