Wednesday, May 11, 2016

Enum and Property file cooperation in Java

Short reminder how to populate Enum in Java with values from property file.

1. Create an Enum as described in example below:

 public enum Users {  
   USER_1, USER_2;  
   private static final String PATH = "/selenium/environment/users.properties";  
   private static Properties properties;  
   private String value;  
   private void init() {  
     if (properties == null) {  
       properties = new Properties();  
       try {  
         properties.load(Users.class.getResourceAsStream(PATH));  
       }  
       catch (Exception e) {  
         e.printStackTrace();  
       }  
     }  
     value = (String) properties.get(this.toString());  
   }  
   public String getValue() {  
     if (value == null) {  
       init();  
     }  
     return value;  
   }  
 }  

Of course it's not an ideal solution and You may come up with better one but this works for me as expected and that's all I need.

2. Create a properties file (short reminder - this file should be placed into resources folder in Your project)

 USER_1=secretlogin1  
 USER_2=secretlogin2  

in this case we have just two entries but You can expand that.

3. Call that from code

 journey.login(Users.USER_1);  

Well it's pretty much it and hopefully this will save me from "googling" next time I'll need such code.

No comments:

Post a Comment