Is it possible, with resource bundles and MessageFormat to have the following result?
getBundle("message.07", "test")
to get "Group test"
getBundle("message.07", null)
to get "No group selected"
Every example I found on the Internet is with planets, with files on the disk and so on.
I only need to check if one parameter is null
(or doesn't exist) in the resource bundle's properties file. I hope to find a special format for the null parameter something like {0,choice,null#No group selected|notnull#Group {0}}
.
The method I use to get the bundles is:
public String getBundle(String key, Object... params) {
try {
String message = resourceBundle.getString(key);
if (params.length == 0) {
return message;
} else {
return MessageFormat.format(message, params);
}
} catch (Exception e) {
return "???";
}
}
I also call this method for other bundles, like
getBundle("message.08", 1, 2)
=> "Page 1 of 2"
(always parameters, no need to check for null
)getBundle("message.09")
=> "Open file"
(no parameters, no need to check for null
)What should I write in my .properties file for message.07
to have the result described?
What I have now is:
message.07=Group {0}
message.08=Page {0} of {1} # message with parameters where I always send them
message.09=Open file # message without parameters
Your .properties
file,
message.07=Group {0}
message.08=Page {0} of {1}
message.09=Open file
message.null = No group selected
And then you need to change your code to put an explicit check params
for null
. And if null
then you can do something like resourceBundle.getString(NULL_MSG)
. Where NULL_MSG
will be this,
private static final String NULL_MSG = "message.null";
So, now your original method would become something like this.
public String getBundle(String key, Object... params) {
String message = null;
try {
if (params == null) {
message = resourceBundle.getString(NULL_MSG);
} else {
message = MessageFormat.format(resourceBundle.getString(key), params);
}
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
Calling my method like below,
getBundle("message.07", "test") // returning 'Group test'
getBundle("message.07", null) // returning 'No group selected'
getBundle("message.08", 1, 2) // returning 'Page 1 of 2'
getBundle("message.08", null) // returning 'No group selected'
getBundle("message.09", new Object[0]) // returning 'Open file'
getBundle("message.09", null) // returning 'No group selected'
Now tell me where is the problem?