java枚举.toString,Java枚举 - 为什么使用toString而不是名字

If you look in the enum api at the method name() it says that:

Returns the name of this enum constant, exactly as declared in its enum declaration.

Most programmers should use the toString method in preference to this one,

as the toString method may return a more user-friendly name.

This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.

Why is better to use toString()? I mean toString may be overridden when name() is already final. So if you use toString and someone overrides it to return a hard-coded value your whole application is down... Also if you look in the sources the toString() method returns exactly and just the name. It's the same thing.

解决方案

It really depends on what you want to do with the returned value:

If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden

If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {

LAST_NAME("Last Name"), FIRST_NAME("First Name");

private final String fieldDescription;

private Fields(String value) {

fieldDescription = value;

}

public String getFieldDescription() {

return fieldDescription;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值