Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate string constants from properties file keys

I'm using .properties files for message internationalization. For example:

HELLO_WORLD = Hello World
HELLO_UNIVERSE = Hello Universe

And then in Java code:

String foo = resourceBundle.getString("HELLO_WORLD");

String literals like "HELLO_WORLD" are problematic because they're error-prone and can't be autocompleted. I'd like to generate code from the keys in the properties file like this:

public interface Messages { // Or abstract class with private constructor
    public static final String HELLO_WORLD = "HELLO_WORLD";
    public static final String HELLO_UNIVERSE = "HELLO_UNIVERSE";
}

And then use it like this:

String foo = resourceBundle.getString(Messages.HELLO_WORLD);

Is there a standard way to do this? I prefer a Maven plugin, but any stand-alone tool that I can run manually would be good enough for my needs.

like image 491
imgx64 Avatar asked Jul 06 '15 06:07

imgx64


2 Answers

Best the other way around:

public enum Message {
    HELLO_WORLD,
    HELLO_UNIVERSE;

    public String xlat(Locale locale) {
        resourceBundle.getString(toString(), locale);
    }
}

Generate from that enum a properties template. This can be repeated for new messages if your base language resides in a separate ..._en.properties.

The generation can be done using values() - without parsing. Though maybe you want to introduce some annotation for properties comments or such.

like image 134
Joop Eggen Avatar answered Sep 22 '22 16:09

Joop Eggen


Following code will generate interface MyProperties in your root directory of the project then after you can use that interface anywhere.

public class PropertiesToInterfaceGenerator {

    public static void main(String[] args) throws IOException {

        Properties properties = new Properties();
        InputStream inputStream =PropertiesToInterfaceGenerator.class.getClassLoader().getResourceAsStream("xyz.properties");
        if(null != inputStream ){
            properties.load(inputStream);
        }
        generate(properties);
    }


    public static void generate(Properties properties) {
        Enumeration e = properties.propertyNames();
        try {
            FileWriter aWriter = new FileWriter("MyProperties.java", true);
            aWriter.write("public interface MyProperties{\n");
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                String val =  properties.getProperty(key);
                aWriter.write("\tpublic static String "+key+" = \""+val+"\";\n");
            }
            aWriter.write(" }\n");
            aWriter.flush();      
            aWriter.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
like image 41
Shekhar Khairnar Avatar answered Sep 22 '22 16:09

Shekhar Khairnar