Java Enums can have behavior?

前端 未结 7 1410
清酒与你
清酒与你 2021-02-02 16:56

In Java, an Enum can do the great things that Enums do, but can also have methods (behavior and logic). What advantage does that have over using a class using an enum? Simple ex

7条回答
  •  广开言路
    2021-02-02 17:09

    In our project, we're using Enums for a few things, but perhaps most prominently for i18n purposes - each piece of shown text is given an Enum. The Enum class has a String-returning method that inspects the Locale that is being used, and picks the correct translation from a collection of translations on runtime.

    This serves as a dual-purpose - you get code completion from your IDE, and also never forget to translate a string.

    The usage is very simple, to the point that it's almost rendundant to give an example, but here's how one might use the translation-enum

    System.out.println(Translations.GREET_PERSON.trans()+" "+user.getName());
    

    Or, if you want to be fancy, have the Enum accept arguments, which will, with some magic string manipulation, be inserted in a marked position in the translations string

    System.out.println(Translations.GREET_PERSON.trans(user.getName());
    

提交回复
热议问题