Locale Messages With ListResourceBundle
Serve localized messages from code-only ListResourceBundle subclasses: getBundle resolves by locale and default-locale fallback stays disabled.
Code
import java.text.MessageFormat;
import java.util.ListResourceBundle;
import java.util.Locale;
import java.util.ResourceBundle;
// 基名 bundle:查不到语言专属类时的兜底(这里是英文)
public class Messages extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return new Object[][] {
{"greeting", "Welcome, {0}!"},
{"farewell", "Goodbye, {0}."}
};
}
public static void main(String[] args) {
for (Locale locale : new Locale[] {Locale.US, Locale.SIMPLIFIED_CHINESE}) {
ResourceBundle bundle = ResourceBundle.getBundle(
"Messages", locale,
// 禁止回退到平台默认 locale:输出与运行机器无关
ResourceBundle.Control.getNoFallbackControl(
ResourceBundle.Control.FORMAT_DEFAULT));
System.out.println(locale + " -> "
+ MessageFormat.format(bundle.getString("greeting"), "Ada"));
}
}
}
// 类名规则:基名 + 下划线 + 小写语言码
class Messages_zh extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return new Object[][] {
{"greeting", "欢迎,{0}!"},
{"farewell", "再见,{0}。"}
};
}
}What the code does
Under the hood: the classes Messages and Messages_zh and the functions getContents and main.
for (Locale locale : new Locale[] {Locale.US, Locale.SIMPLIFIED_CHINESE}) is the loop that carries the per-item work.
Caveats
- Copy, run: the standard library answers every call in the file.
Applying it
Signature: protected Object[][] getContents()
The sequence getContents lives in main; running the file triggers it.
Statements that matter
return new Object[][] {
{"greeting", "Welcome, {0}!"},
{"farewell", "Goodbye, {0}."}
};
return new Object[][] {
{"greeting", "欢迎,{0}!"},
{"farewell", "再见,{0}。"}
};
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- How do you run Locale Messages With ListResourceBundle?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.