从属性文件键生成字符串常量

img*_*x64 6 java code-generation internationalization properties-file

我正在使用.properties文件进行邮件国际化.例如:

HELLO_WORLD = Hello World
HELLO_UNIVERSE = Hello Universe
Run Code Online (Sandbox Code Playgroud)

然后在Java代码中:

String foo = resourceBundle.getString("HELLO_WORLD");
Run Code Online (Sandbox Code Playgroud)

字符串文字是"HELLO_WORLD"有问题的,因为它们容易出错并且无法自动完成.我想从属性文件中的键生成代码,如下所示:

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";
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

String foo = resourceBundle.getString(Messages.HELLO_WORLD);
Run Code Online (Sandbox Code Playgroud)

有没有标准的方法来做到这一点?我更喜欢Maven插件,但我可以手动运行的任何独立工具都足以满足我的需求.

She*_*nar 2

以下代码将生成界面以下代码将在项目的根目录中MyProperties ,然后您可以在任何地方使用该接口。

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)