如何使用 java 声明枚举
我想将这个示例 C# 代码转换为 java 代码:
public enum myEnum {
ONE = "one",
TWO = "two",
};
因为我想将这个常量类更改为枚举
public final class TestConstants {
public static String ONE = "one";
public static String TWO= "two";
}
I want to convert this sample C# code into a java code:
public enum myEnum {
ONE = "one",
TWO = "two",
};
Because I want to change this constant class into enum
public final class TestConstants {
public static String ONE = "one";
public static String TWO= "two";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
简而言之 - 只要提供构造函数参数(并将值设置到相应的字段),您就可以为枚举定义任意数量的参数,
正如 Scott 指出的 - 官方枚举文档给你答案。始终从语言功能和结构的官方文档开始。
更新:对于字符串,唯一的区别是构造函数参数是
String
,并且使用TEST("test")
声明枚举In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)
As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.
Update: For strings the only difference is that your constructor argument is
String
, and you declare enums withTEST("test")
枚举是Java 中的类。它们有一个隐式序数值,从 0 开始。如果您想存储附加字段,那么您可以像任何其他类一样进行操作:
enums are classes in Java. They have an implicit ordinal value, starting at 0. If you want to store an additional field, then you do it like for any other class:
非常简单,如下所示:
有关详细信息,请访问 枚举类型来自 Oracle Java 教程。另外,请记住枚举具有私有构造函数。
更新,由于您更新了帖子,我已将值从
int
更改为String
。相关: Java 字符串枚举。
Quite simply as follows:
For more info, visit Enum Types from Oracle Java Tutorials. Also, bear in mind that enums have private constructor.
Update, since you've updated your post, I've changed my value from an
int
to aString
.Related: Java String enum.
那么,在java中,您还可以创建参数化枚举。假设你想创建一个 className 枚举,你需要在其中存储 classCode 和 className,你可以这样做:
Well, in java, you can also create a parameterized enum. Say you want to create a className enum, in which you need to store classCode as well as className, you can do that like this: