Java enum - why use toString instead of name

后端 未结 7 1985
清酒与你
清酒与你 2020-11-28 22:18

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.

相关标签:
7条回答
  • 2020-11-28 23:01

    While most people blindly follow the advice of the javadoc, there are very specific situations where you want to actually avoid toString(). For example, I'm using enums in my Java code, but they need to be serialized to a database, and back again. If I used toString() then I would technically be subject to getting the overridden behavior as others have pointed out.

    Additionally one can also de-serialize from the database, for example, this should always work in Java:

    MyEnum taco = MyEnum.valueOf(MyEnum.TACO.name());

    Whereas this is not guaranteed:

    MyEnum taco = MyEnum.valueOf(MyEnum.TACO.toString());

    By the way, I find it very odd for the Javadoc to explicitly say "most programmers should". I find very little use-case in the toString of an enum, if people are using that for a "friendly name" that's clearly a poor use-case as they should be using something more compatible with i18n, which would, in most cases, use the name() method.

    0 讨论(0)
提交回复
热议问题