如何在资本化中获得枚举价值
我们创建枚举类,并以完整的大写编写所有枚举成员。
public enum Color {
RED,
YELLOW,
BLACK
}
我们如何在Java中获得资本化的价值(在大写速度中写下单词的第一个字母,以及小写字母的其余字母)。
意思是,当我获取 color
枚举的值时,我应该以 red
, yellow> yellow
, black
来获取
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想使用 ()方法,您别无选择,只能在代码中写入资本化的价值。
如果要获得每种颜色的“显示名称»”,则可以在枚举中添加一个字符串字段,如下示例:
然后,您可以使用
red.displayname
访问大写的名称。 。最后一个解决方案,您可以手动资本化名称,并使用以下代码:
If you want to use java enums name() method, you have no choice but to write the values in Capitalization in your code.
If you want to get a «display name» for each color, you can add a String field to your enum, like in the example below:
Then you can access the capitalized name with
RED.displayName
for example.Last solution, you can manually capitalize the name, with the code below:
枚举不仅可以是简单常数,就像您在摘要中所拥有的那样。查看 https://docs.oracle.com/javase.com/javase.com/javase/tutorial/ java/javaoo/enum.html ,尤其是行星示例。
因此,当然,您可以覆盖ToString()方法,以及您需要的其他任何内容才能运行表示。
An enum can be more than just the simple constant as you have it in your snippet. Check out https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html, especially the planet example.
So of course you can override the toString() method and whatever else you need to get your representation running.
如果您能够使用Apache stringutils,则可以首先使用
string.tolowercase()
,然后string> strignutils.capitalize()
,例如“红色”转换为“红色” “红色”至“红色”。这是您的原始枚举声明:
这是一个示例:
name()
tolowercase(tolowercase()
,并打印该值Capitalize()
带有小写的值,并打印出println()
,因此在这里不全部堆叠输出,这是该代码的输出:
这显示了如何显示进行转换,留下枚举定义是(大写;“红色”等)。
如果您想将其整合到枚举定义本身中,则可以做类似的事情:
并使用这样的事情:
它会产生这样的输出:
If you're able to use Apache StringUtils, you could first use
String.toLowerCase()
, and thenStringUtils.capitalize()
, converting for example "RED" to "red" to "Red".Here's your original enum declaration:
And here's an example that:
name()
toLowerCase()
, and prints that valuecapitalize()
with the lowercase value, and prints that, tooprintln()
so the output isn't all bunched upHere is the output from that code:
This shows how to do the conversion, leaving the enum definitions are they are (uppercase; "RED", etc).
If you'd like to incorporate this into the enum definition itself, you could do something like this:
And use it like this:
Which would produce output like this: