Java enum - why use toString instead of name

后端 未结 7 2061
清酒与你
清酒与你 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 22:45

    A practical example when name() and toString() make sense to be different is a pattern where single-valued enum is used to define a singleton. It looks surprisingly at first but makes a lot of sense:

    enum SingletonComponent {
        INSTANCE(/*..configuration...*/);
    
        /* ...behavior... */
    
        @Override
        String toString() {
          return "SingletonComponent"; // better than default "INSTANCE"
        }
    }
    

    In such case:

    SingletonComponent myComponent = SingletonComponent.INSTANCE;
    assertThat(myComponent.name()).isEqualTo("INSTANCE"); // blah
    assertThat(myComponent.toString()).isEqualTo("SingletonComponent"); // better
    

提交回复
热议问题