繁体   English   中英

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

[英]Generate string constants from properties file keys

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

HELLO_WORLD = Hello World
HELLO_UNIVERSE = Hello Universe

然后在Java代码中:

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

"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";
}

然后像这样使用它:

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

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

最好的反过来:

public enum Message {
    HELLO_WORLD,
    HELLO_UNIVERSE;

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

从该枚举生成属性模板。 如果基本语言位于单独的... ..._en.properties则可以对新消息重复此..._en.properties

可以使用values()完成生成 - 无需解析。 虽然您可能想要为属性注释等引入一些注释。

以下代码将在项目的根目录中生成接口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();
        }
    }
}

不,没有人曾经写过这样的插件,它具有你所有的功能,因为:

  • 国际化可能有很多条目,你最终会得到一个巨大的类,接口,枚举或其他什么,这是不好的。
  • maven / gradle插件会为您生成类,但仅限于编译时。 我看到你提到自动完成 ,这意味着你也需要一个IDE插件,这意味着构建工具(gradle / ant / ...)的插件是不够的。 这些插件之间的交互可能容易出错。
  • 在项目的后期,如果您或您的同事想要一个新的翻译条目,您将不得不重新生成这些类。 这有点累人。

在处理国际化时,建议使用像i18n这样的东西。 如果您不想要新库或项目很小,您可以选择使用eclipse的externalize字符串函数,为此,请参阅

Andriod: 为Android项目外化字符串

其他: help.eclipse.org - Java开发用户指南>参考>向导和对话框> Externalize Strings Wizard

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM