Checking the null parameter in the .properties file for MessageFormat

Is it possible that resource packs and MessageFormat have the following result?

  • when i call getBundle("message.07", "test")to get"Group test"
  • when i call getBundle("message.07", null)to get"No group selected"

Every example I found on the Internet is with planets, with files on disk, etc.

I only need to check if there is one parameter null(or does not exist) in the resource package 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 packages:

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 packages, for example

  • getBundle("message.08", 1, 2)=> "Page 1 of 2"(always parameters, no need to check null)
  • getBundle("message.09")=> "Open file"(no parameters, no need to check for null)

.properties message.07, ?
:

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
+3
2

.properties ,

message.07=Group {0} 
message.08=Page {0} of {1}
message.09=Open file
message.null = No group selected

, params null. null, - resourceBundle.getString(NULL_MSG). NULL_MSG ,

private static final String NULL_MSG = "message.null";

, - .

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

, ,

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'

, ?

0

( getBundle, ).

:

getBundle(param == null? "message.07.null": "message.07", param)

:

getBundleOrNull("message.07", param, "message.07.null")

public String getBundleOrNull(String key, value, nullKey) {
   return getBundle(value == null? nullKey: key: value);
}
+1

Source: https://habr.com/ru/post/1728907/


All Articles