当前位置: 动力学知识库 > 问答 > 编程问答 >

internationalization - How to check if all the keys in a java code are in the bundle?

问题描述:

We are a team who develop a software written in Java, using bundles for internationalization.

We are looking for an analysis tool which can check if all the keys written in the Java Code are in the resource bundle.

This is an example about how it's hard to identify the keys :

Locale locale = new Locale("en", "EN");

ResourceBundle bundle = ResourceBundle.getBundle("MyBundle", locale);

// This is easy to check if the keys are written like this into the Java code.

String myString = bundle.getString("MyKey");

// It's also easy to check this kind of keys

String string1 = "MyKey1";

String string2 = string1;

myString = bundle.getString(string2);

// But it's very hard to check theses keys

String string3 = "MyKey2";

String string4 = string3.toLowerCase();

myString = bundle.getString(string4)

// This one too

String string5 = myfunction();

myString = bundle.getString(string5);

We can pay for a tool or for a plugin for Netbeans but open source is better.

Btw this tool could also be used to find unused keys in the bundle.

网友答案:

The getString(String key) method would throw a MissingResourceException, if the key you're providing is missing in the resource file.

To check whether all the keys you have in the Java code are present in the resource bundle, I suggest to wrap them all in an array, traverse it and check for each of them if the getString(String key) method throws an Exception or not.

String[] keys = new String[]{"key1", "key2"...}; 
for (String key : keys) {
    try {
       String value = bundle.getString(key);
       System.out.println("Key = " + key + "; Value = " + value);
    } catch (MissingResourceException e) {
       System.err.println("No value is found for key = " + key);
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: