Advertisement
MerAll

Basic Localization with Enum with class bodies for constants

Jul 25th, 2014
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. import java.util.Locale;
  2. import java.util.ResourceBundle;
  3.  
  4.  
  5. public class MerLocalizedEnum {
  6.  
  7.     /**In this class, I'm going to localize an enum.
  8.      * Place MerLocBundle.properties and MerLocBundle_sp_MX.properties in base directory of
  9.      * source.
  10.      * @author Meredith
  11.      */
  12.     public MerLocalizedEnum() {
  13.        
  14.         Locale.setDefault(new Locale("sp","MX"));
  15.         for(AnimalEnum ae:AnimalEnum.values()){
  16.             System.out.println(ae.toString());
  17.         }
  18.         Locale.setDefault(new Locale("en","US"));
  19.         for(AnimalEnum ae:AnimalEnum.values()){
  20.             System.out.println(ae.toString());
  21.         }
  22.        
  23.     }
  24.     public static void main(String[] args)
  25.     {
  26.         MerLocalizedEnum mle = new MerLocalizedEnum();
  27.     }
  28.     enum AnimalEnum{
  29.         DOG{
  30.             @Override
  31.             public String getStringRep(ResourceBundle animalNames){
  32.                 return animalNames.getString("DOG");
  33.             }
  34.             },
  35.         CAT{
  36.             @Override
  37.             public String getStringRep(ResourceBundle animalNames){
  38.                 return animalNames.getString("CAT");
  39.             }
  40.             },
  41.         BIRD{
  42.             @Override
  43.             public String getStringRep(ResourceBundle animalNames){
  44.                 return animalNames.getString("BIRD");
  45.             }
  46.             };
  47.            
  48.         private AnimalEnum()
  49.         {
  50.            
  51.         }
  52.    
  53.         public abstract String getStringRep(ResourceBundle animalNames);
  54.         @Override
  55.         public String toString()
  56.         {
  57.             ResourceBundle animNames = ResourceBundle.getBundle("MerLocBundle",Locale.getDefault());
  58.             return this.getStringRep(animNames);
  59.         }
  60.     }
  61.  
  62. }
  63.  
  64. /*Sample output:
  65. "Perro"
  66. "Gato"
  67. "Pájaro"
  68. "Dog"
  69. "Cat"
  70. "Bird"
  71. */
  72.  
  73. /*Properties files:
  74.  MerLocBundle.properties:
  75. DOG="Dog"
  76. CAT="Cat"
  77. BIRD="Bird"
  78.  MerLocBundle_sp_MX.properties:
  79. DOG="Perro"
  80. CAT="Gato"
  81. BIRD="Pájaro"
  82. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement