[英]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();
}
}
}
不,没有人曾经写过这样的插件,它具有你所有的功能,因为:
在处理国际化时,建议使用像i18n这样的东西。 如果您不想要新库或项目很小,您可以选择使用eclipse的externalize字符串函数,为此,请参阅
Andriod: 为Android项目外化字符串
其他: help.eclipse.org - Java开发用户指南>参考>向导和对话框> Externalize Strings Wizard
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.